Java:用流汇总数据

Java: summarize data with streams

是否可以用流来汇总值?例如,我有一个 class 数据集,它为我将一个 csv 文件分成包含以下值的行:

{customer=Max , articlenr=1234, paid=12}
{customer=Lisa , articlenr=21, paid=20}
{customer=Max , articlenr=19, paid=100}

现在我想创建一个带有 Stream 的列表,它给我一个返回客户的列表(没有其他值),按他们曾经支付过的金额排序(在这个例子中,Max 支付了 112,Lisa 支付了 20 ). 所以我希望 Max 在 List 和 Lisa 中排在第一位。

paid 的总和收集到 Map<String, Integer>,然后将条目流式传输,按付费倒序排序,然后将密钥收集到 List.

List<MyClass> records; // your list

List<String> customers = records.stream()
        .collect(groupingBy(MyClass::getCustomer, Collectors.summingInt(MyClass::getPaid)))
        .entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
        .map(Map.Entry::getKey)
        .collect(toList());

是的,有可能:

public class Customer {
    private String name;
    private int articlenr;
    private int paid;
}

现在,您可以像这样获取姓名列表,按支付总额排序:

List<String> names = customerList.stream().sorted(Comparator.comparing(Customer::getPaid)).map(Customer::getName).collect(Collectors.toList());

这几天我写了一篇关于如何使用 Streams 的文章和一些更多的例子:http://petrepopescu.tech/2021/01/simple-collection-manipulation-in-java-using-lambdas/