我的地图结构如下
Map<String, Set<String> myMapOfSets = new HashSet<>():
这张地图是400码的。而这400套中的每一套都可以大小在100到10000元素之间。这些集合中的许多元素正在重复。我希望找到前10元素,其中最受欢迎的这400套。如何实现这一点?谢谢你的帮助。
发布于 2017-07-06 04:26:45
使用Java 8流:
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);输出
C=6
B=4
D=4发布于 2017-07-06 03:45:40
如果这是与家庭作业有关的,这里有一些提示:
假设映射可以作为一组集合来处理,并且字符串键arn不相关。
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.你现在有了一张事件的地图,
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.https://stackoverflow.com/questions/44939202
复制相似问题