Java 8 Stream数据处理案例

Java 8 Stream数据处理的案例,工作中常用到的,方便查阅

Posted by Steven on 2020-08-27

取list中所有对象的某个字段先绝对值后的最大值得对象

1
2
3
4
Optional<QuestionnaireResult> userOp = list.stream().map((x) -> {
x.setScore(Math.abs(x.getScore()));
return x;
}).max(Comparator.comparingDouble(QuestionnaireResult::getScore));

过滤对象集合中对象字段满足条件的对象集合

1
List<OctoSupplierProductMapping> ospm = octoSupplierProductMappings.stream().filter(o -> o.getUsed() == 0).collect(Collectors.toList());

List中的最大值对象

1
2
Optional<Employee > userOp= userList.stream().max(Comparator.comparingInt(Employee ::getAge));
Employee maxEmp = userOp.get();

或者

1
2
3
Optional<Employee > userOp= userList.stream().filter(Objects::nonNull).filter(item -> item.getAge() != null)
.sorted(Comparator.comparing(Employee::getAge).reversed()).findFirst().get();
Employee maxEmp = userOp.get();

避免空指针,添加一个filter,判断age不能为空,

1
filter(item -> item.getAge() != null)

或者使用orElse防止空指针。

1
2
Optional<Employee > userOp= employees.stream().filter(Objects::nonNull).max(Comparator.comparingInt(Employee ::getAge));
Employee maxEmp = userOp.orElse(new Employee());

按照多字段分组

1
Map<String, List<AgentStorageReports>> stringListMap = agentStorageReportsList.stream().collect(Collectors.groupingBy(o -> o.getInitiatorTanantId() + "_" + o.getInitiatorJobNum()));

Java从list对象集合中获取某一列的集合数据

1
2
3
4
5
6
7
List<Book> list = Lists.newArrayList();

list.add(new Book("1", "sql基础大全", 200));
list.add(new Book("2", "Java基础", 500));
System.out.println(list);
List<String> nameList = list.stream().map(Book -> Book.getName()).collect(Collectors.toList());
System.out.println(nameList);

推荐文章