Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert list to multiple lists and storing it in Map using JAVA 8(streams) based on the data

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks in advance.

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading