collect:可以将stream元素转换为不同类型的结果(List, Set , Map)
转list(需要set而不是list,使用Collectors.toSet()):
List personList = Arrays.asList(
new Person(1, 18, "小明"),
new Person(1, 19, "小强"),
new Person(1, 20, "小刚"),
new Person(1, 19, "小王"))
.stream()
.filter(person -> {
System.out.println("filter:"+person.getName());
return person.getAge() == 19;
})
.collect(Collectors.toList());
personList.forEach(person -> System.out.println(person.getName()));
转map:
Map<Integer, List<Person>> personMap = Arrays.asList(
new Person(1, 18, "小明"),
new Person(1, 19, "小强"),
new Person(1, 20, "小刚"),
new Person(1, 19, "小王"))
.stream()
.collect(Collectors.groupingBy(p->p.getAge()));
personMap.forEach((age,person)-> System.out.println(age+":"+person));
控制台输出:
18:[Person{id=1, age=18, name='小明'}]
19:[Person{id=1, age=19, name='小强'}, Person{id=1, age=19, name='小王'}]
20:[Person{id=1, age=20, name='小刚'}]
flatMap:将stream的每个元素转换到其他对象的Stream。因此,每个对象将被转换为零个、一个或多个基于Stream的不同对象。这些stream的内容将被放置到flatMap操作的返回Stream中
List foos = new ArrayList<>();
// create foos
IntStream
.range(1, 4)
.forEach(i -> foos.add(new Foo("Foo" + i)));
// create bars
foos.forEach(f ->
IntStream
.range(1, 4)
.forEach(i -> f.bars.add(new Bar("Bar" + i + " <- " + f.name))));
//至此foos拥有3个Foo,每个Foo拥有3个Bar。下列代码将生成9个Bar
foos.stream()
.flatMap(f -> f.bars.stream())
.forEach(b -> System.out.println(b.name))
Reduce:将stream的所有元素合并到一个结果中
List personList = Arrays.asList(
new Person(1, 18, "小明"),
new Person(1, 19, "小强"),
new Person(1, 20, "小刚"),
new Person(1, 19, "小王"))
.stream()
.collect(Collectors.toList());
personList.stream()
.reduce((p1, p2) -> {
System.out.println("p1==="+p1);
System.out.println("p2==="+p2);
return p1.getAge() > p2.getAge() ? p1 : p2;
})
.ifPresent(System.out::println);
控制台输出:
p1===Person{id=1, age=18, name='小明'}
p2===Person{id=1, age=19, name='小强'}
p1===Person{id=1, age=19, name='小强'}
p2===Person{id=1, age=20, name='小刚'}
p1===Person{id=1, age=20, name='小刚'}
p2===Person{id=1, age=19, name='小王'}
Person{id=1, age=20, name='小刚'}