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
});