描述
stream是高级iterator,只能遍历一次。可以有多个中间操作,只能有一个终端操作。
source->intermediate->terminal
代码
@Test
public void testFlatMap() {
List<Student> student1 = new ArrayList<>(Arrays.asList(new Student("2"), new Student("1"), new Student("4")));
List<Student> student2 = new ArrayList<>(Arrays.asList(new Student("5"), new Student("3"), new Student("7")));
List<Student> student3 = new ArrayList<>(Arrays.asList(new Student("9"), new Student("8"), new Student("6")));
List<List<Student>> lists = new ArrayList<>(Arrays.asList(student1, student2, student3));
List<Student> collect = lists.stream()
.flatMap(list -> list.stream())
.sorted((s1, s2) -> s1.getName().compareTo(s2.getName()))
.collect(Collectors.toList());
System.out.println(collect);
// [Student(name=1), Student(name=2), Student(name=3), Student(name=4), Student(name=5), Student(name=6), Student(name=7), Student(name=8), Student(name=9)]
}
引用
https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html
网友评论