我的地图结构如下
Map<String, Set<String> myMapOfSets = new HashSet<>():
此地图的大小为400.这400套中的每一套都可以是100到10000个元素之间的任何大小。这些集合中的许多元素都在重复。我希望找到这400套中最受欢迎的十大元素。如何实现?谢谢你的帮助。
答案 0 :(得分:1)
使用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
答案 1 :(得分:0)
如果这是与家庭作业相关的,这里有一些提示:
假设可以将地图视为一组集合,并且字符串键不相关。
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.