1

I have a list of objects and I want to divide this list into two lists based on the value of a field. Here's how I did it with Stream.filter():

public void setMovieMedia(List<MovieMediaResponse> movieMedias) {

    // fill the first list
    this.setPhotos(movieMedias
            .stream()
            .filter(movieMedia -> movieMedia.getType().equals(MediaType.PHOTO))
            .collect(Collectors.toList()));
    // fill the second list
    this.setVideos(movieMedias
            .stream()
            .filter(movieMedia -> movieMedia.getType().equals(MediaType.VIDEO))
            .collect(Collectors.toList()));
}

However, with this approach, I think I am looping through the list twice. Is there a way to do achieve the same thing without iterating through the list twice?

PS: I know I can achieve this by using List.forEach() like in the following example, but I'd like to avoid using this method:

List<MovieMediaResponse> movieMedias = ...;
movieMedias.forEach(m -> {
    if (m.getType().equals(MediaType.PHOTO))
        // append to list1
    else if (m.getType().equals(MediaType.VIDEO))
       // append to list2
});
Janus Varmarken
  • 2,306
  • 3
  • 20
  • 42
Ayoub k
  • 7,788
  • 9
  • 34
  • 57

1 Answers1

3

What you are looking for is Collectors.partitioningBy that will get you a Map where key is a Boolean; thus you can do:

result.get(true/false) 

to get each individual list. Since you seem to know your way around streams, I will not show an example, you can most probably figure it out

Eugene
  • 117,005
  • 15
  • 201
  • 306