<分区>
我有一个对象列表,我想根据字段的值将这个列表分成两个列表。以下是我如何使用 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()));
}
但是,使用这种方法,我认为我在列表中循环了两次。有没有一种方法可以在不遍历列表两次的情况下实现同样的事情?
PS:我知道我可以通过使用 List.forEach()
来实现这一点,就像下面的例子一样,但我想避免使用这种方法:
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
});