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

 

先创建一个测试类

public class TestEntity {

    private Long id;

    private String name;

    private Long age;

    //省略get set方法
}

构造一个列表

        List<TestEntity> 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<Long, List<TestEntity>> entityMapById = testEntityList.stream().collect(Collectors.groupingBy(TestEntity::getId));

 过滤出年龄为16的元素

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

 

  

 

相关文章:

  • 2021-11-25
  • 2022-12-23
  • 2021-10-21
  • 2021-07-30
  • 2021-05-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-25
猜你喜欢
  • 2022-02-08
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-02
  • 2022-12-23
相关资源
相似解决方案