stream流收集多个list的某字段的集合

我这用的是mongodb收集code字段,根据业务调整《DocuLib.getCode(doc)》字段即可。

        List<Document> materialRequisitionList =
                DBUtils.list(materialRequisition.collectionName, new Document("ptCode.id", code));
        List<Document> repairMaterialRequisitionList =
                DBUtils.list(repairMaterialRequisition.collectionName, new Document("ptCode.id", code));

        List<String> codeList =
                Stream.concat(
                                materialRequisitionList.stream().map(doc -> DocuLib.getCode(doc)),
                                repairMaterialRequisitionList.stream().map(doc -> DocuLib.getCode(doc)))
                        .collect(Collectors.toList());
### 使用Java Stream API按字段对列表进行分组并收集到映射 为了实现基于对象某个字段的分组操作并将结果收集至`Map`,可以利用`Collectors.groupingBy()`方法。此方法允许指定分类函数作为参数来定义分组依据[^1]。 下面是一个具体的例子,假设有一个名为`Employee`的对象类,其中包含员工的名字(`name`)、部门(`dept`)以及工资(`salary`)属性: ```java import java.util.*; import java.util.stream.Collectors; class Employee { private String name; private String dept; private double salary; public Employee(String name, String dept, double salary) { this.name = name; this.dept = dept; this.salary = salary; } // Getters... @Override public String toString() { return "Employee{name='" + name + "', dept='" + dept + "', salary=" + salary + '}'; } } public class Main { public static void main(String[] args) { List<Employee> employees = Arrays.asList( new Employee("Alice", "HR", 7000), new Employee("Bob", "Engineering", 9000), new Employee("Charlie", "HR", 6500) ); Map<String, DoubleSummaryStatistics> result = employees.stream() .collect(Collectors.groupingBy(Employee::getDept, Collectors.summarizingDouble(Employee::getSalary))); System.out.println(result); } } ``` 上述代码展示了如何通过`groupingBy`按照部门名称分组,并且对于每一个分组计算该部门内所有成员薪资的相关统计信息(如平均数、总数等),这里使用的是`summarizingDouble`收集器。 如果目标是在分组的同时执行多种聚合运算,则可以通过嵌套收集器的方式完成。例如,在同一个分组下既求得某字段之和又获取其均值: ```java Map<String, Tuple<Double, Double>> complexResult = employees.stream() .collect(Collectors.groupingBy(Employee::getDept, Collectors.collectingAndThen( Collectors.teeing( Collectors.summingDouble(Employee::getSalary), Collectors.averagingDouble(Employee::getSalary), (total, avg) -> new Tuple<>(total, avg)) ) )); ``` 在这个复杂版本的例子中,引入了一个自定义的二元组(Tuple)用于存储两个不同类型的聚合结果——总和与平均值。需要注意的是,实际项目里可能需要创建这样的辅助类或采用其他形式的数据结构来容纳多维度的结果数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值