首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在多个集合中找到最流行的元素

如何在多个集合中找到最流行的元素
EN

Stack Overflow用户
提问于 2017-07-06 03:16:09
回答 2查看 134关注 0票数 1

我的地图结构如下

Map<String, Set<String> myMapOfSets = new HashSet<>():

这张地图是400码的。而这400套中的每一套都可以大小在100到10000元素之间。这些集合中的许多元素正在重复。我希望找到前10元素,其中最受欢迎的这400套。如何实现这一点?谢谢你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-06 04:26:45

使用Java 8流:

代码语言:javascript
复制
Map<String, Set<String>> myMapOfSets = new HashMap<>();
myMapOfSets.put("K1", new HashSet<>(Arrays.asList("A", "B", "C",      "E"     )));
myMapOfSets.put("K2", new HashSet<>(Arrays.asList(     "B", "C", "D",      "F")));
myMapOfSets.put("K3", new HashSet<>(Arrays.asList("A",      "C",      "E", "F")));
myMapOfSets.put("K4", new HashSet<>(Arrays.asList(     "B", "C", "D"          )));
myMapOfSets.put("K5", new HashSet<>(Arrays.asList("A",      "C", "D"          )));
myMapOfSets.put("K6", new HashSet<>(Arrays.asList(     "B", "C", "D", "E", "F")));

List<Entry<String, Long>> result =           // change to List<String> if you only want values
        myMapOfSets.values()
                   .stream()
                   .flatMap(Set::stream)
                   .collect(Collectors.groupingBy(s -> s, Collectors.counting()))
                   .entrySet()
                   .stream()
                   .sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // descending
                   .limit(3)                 // change to 10 for your code
                // .map(Map.Entry::getKey)   // uncomment if you only want values
                   .collect(Collectors.toList());
result.forEach(System.out::println);

输出

代码语言:javascript
复制
C=6
B=4
D=4
票数 1
EN

Stack Overflow用户

发布于 2017-07-06 03:45:40

如果这是与家庭作业有关的,这里有一些提示:

假设映射可以作为一组集合来处理,并且字符串键arn不相关。

代码语言:javascript
复制
Create a new map called scores, store strings and ints
Iterate over the sets
   Iterate over the values of a set
     get the value of the string from scores defaulting to 0, and add 1.

你现在有了一张事件的地图,

代码语言:javascript
复制
create a list of mapentries of length 10, keep it sorted.
Loop over the map
   if the current value is higher then the min value in the list, replace the lowest value, and keep track of the new minimumscore.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44939202

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档