java stream用法


本文介绍取出列表中元素某一个属性的最大值,最小值,及按某个元素分组

先创建一个测试类

public class TestEntity {

    private Long id;

    private String name;

    private Long age;

    //省略get set方法
}

构造一个列表

        List testEntityList = new ArrayList<>();
        testEntityList.add(buildTestEntity(1L, "张三", 18L));
        testEntityList.add(buildTestEntity(2L, "李四", 17L));
        testEntityList.add(buildTestEntity(3L, "王五", 19L));
        testEntityList.add(buildTestEntity(4L, "赵六", 16L));

取出年龄最大值

Long maxAge = testEntityList.stream().mapToLong(TestEntity::getAge).max().getAsLong();

取出年龄最小值

Long minAge = testEntityList.stream().mapToLong(TestEntity::getAge).min().getAsLong();

按id分组

Map> entityMapById = testEntityList.stream().collect(Collectors.groupingBy(TestEntity::getId));

 过滤出年龄为16的元素

List entityList = testEntityList.stream().filter(entity -> entity.getAge() == 16).collect(Collectors.toList());