简体   繁体   English

使用 Java 8 获取集合中所有项目的最常用名称的正确方法

[英]Correct way to get the most common name of all items in a Set using Java 8

I am currently trying to find the best way to find the most common name from all items in a Set.我目前正在尝试找到从集合中的所有项目中找到最常见名称的最佳方法。

The object in a Set are Person objects: Set 中的对象是 Person 对象:

public class Person {
     private String name;

     ...

     public String getName() {
          return name;
     }
}

In the method findMostCommonName, I want to find the most common name of all the Person objects in the given set.在 findMostCommonName 方法中,我想找到给定集合中所有 Person 对象的最常见名称。 Is there a Java 8 way to do that?有没有 Java 8 的方法来做到这一点?

public String findMostCommonName(Set<Person> personSet) {

//Code here

}

Thanks.谢谢。

You can use 您可以使用

public String findMostCommonName(Set<Person> personSet) {
    return personSet.stream().map(Person::getName)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet().stream()
        .max(Map.Entry.comparingByValue()).map(Map.Entry::getKey)
        .orElse(null);
}

personSet.stream().map(Person::getName) straight-forwardly creates a stream of name strings, .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) counts the number of occurences into a Map<String,Long> , then .entrySet().stream() will stream over the entries and .max(Map.Entry.comparingByValue()).map(Map.Entry::getKey) will find the entry with the highest value, ie count, and extract the key, which is the string with that count. personSet.stream().map(Person::getName)直接创建一个名称字符串流.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))将出现的次数计数为Map<String,Long> ,然后.entrySet().stream()将对条目进行.entrySet().stream() .max(Map.Entry.comparingByValue()).map(Map.Entry::getKey)将找到具有最高条目的条目值,即计数,并提取密钥,即具有该计数的字符串。

The last .orElse(null) determines how to handle the situation when there is no result, ie personSet is empty. 最后一个.orElse(null)确定在没有结果(即personSet为空.orElse(null)如何处理情况。 If you use get() instead, a NoSuchElementException will be thrown in that case. 如果改用get() ,则在这种情况下将引发NoSuchElementException

In case of a tie, an arbitrary name out of the names with the highest number of occurrences will be returned. 如果出现平局,将返回出现次数最多的名称中的任意名称。

您可以使用嵌套循环并使用equals方法遍历集合以比较名称,如果它返回true,则将+1添加到计数器中并保持名称多次出现,或者可以使用键/值对象(例如HashMap和存储每个名称出现的次数

public String findMostCommonName(Set<Person> personSet) {
    return personSet.stream().parallel().map(Person::getName)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet().stream().parallel()
        .max(Map.Entry.comparingByValue()).map(Map.Entry::getKey)
        .orElse(null);
}

Just added Parallelism to speed up the code by around 1.2x刚刚添加了 Parallelism 以将代码加速约 1.2 倍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM