【问题标题】:collecting the sum of a field in java stream收集java流中字段的总和
【发布时间】:2019-03-01 03:13:42
【问题描述】:

考虑以下类:

public class PersonalExpense {
    private String name;
    private int currentExpenses;

    ...

如何编写与第一种方法 (getRemainingCompanyBalance) 工作方式相同的 java 流“管道”。此代码导致错误。

该列表包含每个部门的单独列表。子列表中的每个条目都是该类的一个实例。名称/费用:

de#1first"/9900, de#1second"/8700, de#2first"/8500, de#2second"/10000, de#3first"/7800, de#3second"/6900

    private static long getRemainingCompanyBalance ( long initialBalance, List<ArrayList<PersonalExpense>> total) {
        long remainingBalance = initialBalance;
        for (List<PersonalExpense> departmentExpense : total) {
            for (PersonalExpense personalExpense : departmentExpense) {
                System.out.println(personalExpense.getName());
                remainingBalance = remainingBalance - personalExpense.getCurrentExpenses();
            }
        }
        return remainingBalance;
    }

    public static long getRemainingCompanyBalanceLambda ( long initialBalance, List<ArrayList<PersonalExpense>> total) {
        long remainingBalance = initialBalance;


        Integer sum = total
        .stream()
        .flatMap(Collection::stream)
        .filter(pe -> pe instanceof PersonalExpense)
        .map (pe -> (PersonalExpense) pe)
        .collect(Collectors.toList())
        .mapToInt(PersonalExpense::getCurrentExpenses)
        .sum();


        return remainingBalance -= sum;
    }

}

我正在尝试收取费用,然后从余额中减去这些费用

【问题讨论】:

  • 嗯我个人不认为这是重复的,它不像计算 sum 那样简单,特别是因为 OP 似乎不知道 flatMap 之类的......

标签: java lambda java-stream


【解决方案1】:
public static long getRemainingCompanyBalanceLambda ( long initialBalance, List<ArrayList<PersonalExpense>> total) {

   int sum = total.stream()
        .flatMap(List::stream)
        .mapToInt(PersonalExpense::getCurrentExpenses)
        .sum();

   return initialBalance - sum;

}

【讨论】:

    【解决方案2】:

    你有一些不必要的方法调用。您不需要过滤Stream,因为它已经只包含PersonalExpense 实例,并且您不应该将它收集到List,因为这会阻止您将其映射到IntStream 和计算总和。

    public static long getRemainingCompanyBalanceLambda ( long initialBalance, List<ArrayList<PersonalExpense>> total) {
        return initialBalance - total
        .stream()
        .flatMap(Collection::stream)
        .mapToInt(PersonalExpense::getCurrentExpenses)
        .sum();
    }
    

    【讨论】:

    • @Eugene 这是真的
    猜你喜欢
    • 2019-09-19
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多