有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用流解释的Java8方法

我对Java8有点陌生,我正在尝试理解下面的代码是做什么的

@Override
public Optional<String> getMostFrequentLastName(final List<User> users) {
    return 
      users.stream()
       .collect(Collectors.groupingBy(User::getLastName, Collectors.counting()))
       .entrySet()
       .stream()
       .filter(entry -> entry.getValue() >= 2)
       .reduce((e1, e2) -> 
           e1.getValue() < e2.getValue() ? e2 :
           e1.getValue() > e2.getValue() ? e1 :
           new AbstractMap.SimpleEntry<>(null, e1.getValue()))
       .map(Map.Entry::getKey);
}

有人能详细解释一下这是怎么回事吗


共 (1) 个答案

  1. # 1 楼答案

    The most confusing i think for me is the reduce and map parts

    这里的reduce操作非常混乱:

            .reduce((e1, e2) -> e1.getValue() < e2.getValue() ? e2 :
                    e1.getValue() > e2.getValue() ? e1 :
                            new AbstractMap.SimpleEntry<>(null, e1.getValue()))
    

    我想说的是,这在一定程度上混淆了格式:

        .reduce(
            (e1, e2) ->
                e1.getValue() < e2.getValue()
                    ? e2
                    : e1.getValue() > e2.getValue()
                        ? e1
                        : new AbstractMap.SimpleEntry<>(null, e1.getValue()))
    

    (但只是部分)

    记住e*.getValue()是一个名字出现的次数。这是说:

    • 如果name1出现的次数少于name2,那么name2是迄今为止我们找到的最好的名字
    • 如果name2出现的次数比name1多,那么name1是我们迄今为止找到的最好的名字
    • 否则,它们出现的次数是相同的——在本例中,请组成一个新名称null,并将其与出现的次数一起返回

    返回名称null有点令人困惑,因为不知道您的要求——看起来这实际上是为了找到出现次数最多的名称,但前提是没有其他出现次数最多的名称

    reduce将返回一个Optional<Map.Entry<String, Long>>(如果列表中至少有一个人,则会返回)。随后的.map(Map.Entry::getKey)只提取名称并丢弃计数

    请注意,在许多名称出现最大计数的情况下,getKey返回null,这意味着方法总体返回Optional.empty()