如何使用 java 8 查找对象的最大形式自定义对象

How to find maximum form custom object of objects using java 8

我有对象列表(请忽略语法我已经更改了名称,代码编译良好)

List<Employees> list=Arrays.asList(new Employee(),new Employee() ........ nth new Employee());
Employee
{
 String name;
 String address;
 .
 .
 .
 String phone;
 IncomeSRC1 src1;
 IncomeSRC2 src2;
 IncomeSRC3 src3;
}
IncomeSRC1{
String details;
double amount;
.
.
.
}
IncomeSRC2{
String details;
double amount;
.
.
.
}
IncomeSRC3{
String details;
double amount;
.
.
.
}

我想使用 Java8 从每个收入源中找到列表中的最大金额,可以使用 单一 流来实现吗?

如果我没理解错的话,你可以这样做。首先提取每个员工的 income 属性,然后使用具有三个参数的 toMap 收集器找到每个收入来源的最大金额。

这种方式的优点是在单流中进行,缺点是有点硬编码。

Map<String, Double> result = 
list.stream()
    .map(employee -> Arrays.asList(
          new AbstractMap.SimpleEntry<>("src1", employee.getSrc1().getAmount()),
          new AbstractMap.SimpleEntry<>("src2", employee.getSrc2().getAmount()),
          new AbstractMap.SimpleEntry<>("src3", employee.getSrc3().getAmount())
     ))
   .flatMap(List::stream)
   .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Double::max));

其他方式是这样的:

List<Optional<Double>>  result =   Stream.of(
            list.stream().map(Employee::getSrc1).map(IncomeSRC1::getAmount)
                .max(Double::compareTo),
            list.stream().map(Employee::getSrc2)
                .map(IncomeSRC2::getAmount).max(Double::compareTo),
            list.stream().map(Employee::getSrc3)
                .map(IncomeSRC3::getAmount).max(Double::compareTo)
    ).collect(Collectors.toList());

我测试了答案,它符合我最初的要求, 反正这里是答案(名称已更改,编译成功 returns 有效答案)

AtomicReference<Double> src1 = new AtomicReference<>();
AtomicReference<Double> src2 = new AtomicReference<>();
AtomicReference<Double> src3 = new AtomicReference<>();
        src1.set(0d);
        src2.set(0d);
        src3.set(0d);
        list.stream().forEach(
                i-> {
                    //add null checks and other business logic 
                    if( i.getIncomeSRC1().getAmount() >src1.get()) src1.set( i.getIncomeSRC1().getAmount());
                    if( i.getIncomeSRC2().getAmount() >src2.get()) src2.set( i.getIncomeSRC2().getAmount());
                    if( i.getIncomeSRC3().getAmount() >src3.get()) src3.set( i.getIncomeSRC3().getAmount());
                }
                );