将Collectors maxBy与groupingBy一起使用时,可选的Unwrap [英] Unwrap Optional when using Collectors maxBy with groupingBy

查看:939
本文介绍了将Collectors maxBy与groupingBy一起使用时,可选的Unwrap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Stringint字段的类.

I have a class with a String and an int field.

public class Data {
    private String name;
    private int value;

    private Data(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public int getValue() {
        return value;
    }
}

我有一个List<Data>,如果我想创建一个映射(分组)以了解每个名称最大值的数据对象,我可以这样做,

I have a List<Data> and if I want to create a map (grouping) to know the Data object with maximum value for each name, I could do like,

Map<String, Optional<Data>> result = list.stream()
            .collect(Collectors.groupingBy(Data::getName,
                    Collectors.maxBy(Comparator.comparing(Data::getValue))));

但是,由于Collectors.maxBy的约定,RHS被包裹在一个Optional中,但是我想要一个Map<String, Data>.

But, the RHS is wrapped in an Optional because of the contract of Collectors.maxBy but I want a Map<String, Data>.

我可以想到一个使用Collectors.collectingAndThen的选项,但是我将不得不创建一个不必要的中间图.

One option I could think of it to use Collectors.collectingAndThen, but I will have to create an unnecessary intermediate map.

list.stream()
         .collect(Collectors.collectingAndThen(Collectors.groupingBy(Data::getName,
                Collectors.maxBy(Comparator.comparing(Data::getValue))),
                map -> map.entrySet().stream()
                        .collect(Collectors.toMap(Map.Entry::getKey,
                                 e -> e.getValue().get()))));

是否有惯用的方式使用流来实现这一目标?

Is there an idiomatic way to achieve this using streams?

推荐答案

您可以将BinaryOperator.maxByCollectors.toMap

Map<String, Data> result = list.stream()
        .collect(Collectors.toMap(Data::getName, Function.identity(),
            BinaryOperator.maxBy(Comparator.comparing(Data::getValue))));

这篇关于将Collectors maxBy与groupingBy一起使用时,可选的Unwrap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆