//假设有一个Person类
public class Person {
private String name;
private Integer age;
private Integer id;
// 构造器、getter和setter省略
}
List<Person> people = Arrays.asList(
new Person("Alice", 24 ,1),
new Person("Bob", 30 ,2),
new Person("Charlie", 24 ,3),
new Person("David", 28, 4)
);
(1)分组
1.1 对象属性分组
可以按照年龄来分组
people.stream().collect(Collectors.groupingBy(Person::getAge));
1.2 多级分组
首先按照年龄分组,然后在每个年龄组内再按照名字分组。
people.stream()
.collect(
Collectors.groupingBy(
Person::getAge,
Collectors.groupingBy(Person::getName)
)
);
1.3 分组后的其他操作
1.3.1 分组后的结果进行操作,例如计算每个组的元素数量:
people.stream()
.collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));
1.3.2 对每个分组进行其他聚合操作,例如求平均值:
people.stream()
.collect(Collectors.groupingBy(Person::getAge, Collectors.averagingInt(Person::getAge)));
(2)List转Map
2.1 可以按照id
属性将列表转换为Map,映射id,name
people.stream()
.collect(Collectors.toMap(Person::getId, Person::getName))
如果列表中有两个具有相同键的元素,直接使用toMap
会抛出IllegalStateException
。为了处理键冲突,可以提供第三个参数,一个合并函数:
people.stream()
.collect(Collectors.toMap(
Person::getId,
Person::getName,
(existing, replacement) -> existing
));
2.2 转换为自定义类型的Map,例如TreeMap
people.stream()
.collect(Collectors.toMap(
Person::getId,
Person::getName,
(existing, replacement) -> existing,
TreeMap::new
));
2.3 可以按照id
属性将列表转换为Map,映射id,Person对象
people.stream()
.collect(Collectors.toMap(Person::getId, Function.identity()));
people.stream()
.collect(Collectors.toMap(Person::getId, p -> p,
(newKey, oldKey) -> oldKey));
(3)去重
3.1 根据属性name去重
people.stream().filter(o -> o.getName() != null).collect(
Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(o -> o.getName()))), ArrayList<Person>::new));
(4) List对象集合中求和、最大、最小、平均的统计
4.1 mapToInt
people.stream().mapToInt(Apple::getAge).sum(); //和
people.stream().mapToInt(Apple::getAge).max(); //最大
people.stream().mapToInt(Apple::getAge).min(); //最小
people.stream().mapToInt(Apple::getAge).average(); //平均值
4.2 除了统计int类型,还有double(mapToDouble)和long(mapToLong)
(5) 实现List对象集合的分页(skip()+limit())
people.stream().skip(pageSize * (pageNum - 1)).limit(pageSize).collect(Collectors.toList());
(6)实现List对象集合的简单过滤(过滤年龄不为 null 的对象)
people.stream().filter(x -> x.getAge() != null).collect(Collectors.toList());