引言
首先我们定义一个类名为People,如下:
static class People{
private String name;
private Integer id;
private Integer classId;
public People(String name, Integer id,Integer classId) {
this.name = name;
this.id = id;
this.classId = classId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", id=" + id +
", classId=" + classId +
'}';
}
}
groupingBy
groupingBy其实类似于SQL里的group by语句,不过groupingBy将返回的结果封装到 Collector<T, ?, Map<K, List>>,其中T是传入的参数类型,K是groupingBy的键。
import java.util.*;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
Integer id = 0;
List<People> list = Arrays.asList(
new People("a", ++id,1),
new People("b", ++id,2),
new People("c", ++id,2),
new People("d", ++id,3),
new People("e", ++id,3),
new People("f", ++id,3)
);
// select SUM(id) from People group by classId;
Map<Integer, List<People>> collect = list.stream()
.collect(Collectors.groupingBy(People::getClassId));
collect.forEach((K,V)->{
System.out.println(K + " : " + V);
System.out.println(K + " : " + V.stream().collect(Collectors.summarizingInt(People::getId)).getSum());
});
}
// 省略刚刚的 static class People
}
输出结果为:
1 : [People{name='a', id=1, classId=1}]
1 : 1
2 : [People{name='b', id=2, classId=2}, People{name='c', id=3, classId=2}]
2 : 5
3 : [People{name='d', id=4, classId=3}, People{name='e', id=5, classId=3}, People{name='f', id=6, classId=3}]
3 : 15
partitioningBy
partitioningBy根据判断条件是否满足将原本的流分为TRUE和FALSE映射的两个集合,返回的是Collector<T, ?, Map<Boolean, List>>,其中T是传入的参数类型。
public static void main(String[] args) {
Integer id = 0;
List<People> list = Arrays.asList(
new People("a", ++id,1),
new People("b", ++id,2),
new People("c", ++id,2),
new People("d", ++id,3),
new People("e", ++id,3),
new People("f", ++id,3)
);
Map<Boolean, List<People>> collect = list.stream()
.collect(Collectors.partitioningBy(x -> x.getClassId() == 3));
System.out.println("TRUE: " );
collect.get(Boolean.TRUE).forEach(System.out::println);
System.out.println("FALSE: " );
collect.get(Boolean.FALSE).forEach(System.out::println);
}
输出结果:
TRUE:
People{name='d', id=4, classId=3}
People{name='e', id=5, classId=3}
People{name='f', id=6, classId=3}
FALSE:
People{name='a', id=1, classId=1}
People{name='b', id=2, classId=2}
People{name='c', id=3, classId=2}