javajava-8java-stream

Convert List to a Map<Boolean, List> using Java streams


Suppose I have below response class which collect response and some other data.

class Response{
    Boolean status;
    String message;
    Integer id;

    Response(Boolean s, String m, Integer id)
    {
        status=s;
        message=m;
        this.id=id;
    }
    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        id = id;
    }
}

List data as below:

List<Response> response = new ArrayList<Response>();
response.add(new Response(Boolean.TRUE,"HelloTrue",1));
response.add(new Response(Boolean.FALSE,"HelloFalse",2));

I want result as two different list based on status type(TRUE,FALSE) using single stream() method. e.g:

Map<Boolean,List<Response>> responsesResult=response.stream().....

Solution

  • You can collect it using Collectors.partitioningBy(), this way:

    Map<Boolean, List<Response>> responsesResult = response.stream()
        .collect(Collectors.partitioningBy(Response::getStatus));