所以我有一份清单
List<String> names = new ArrayList<String>();
names.add("Mike");
names.add("Matthew");
names.add("Kelly");
names.add("Elon");
names.add("Paul");
names.add("Paul");
names.add("Paul");
names.add("Paul");
names.add("Kelly");我需要清点所有的名字,然后按降序打印出3个最受欢迎的名字
Output:
Paul : 4
Kelly : 2
Mike : 1我都试了些什么?我尝试了从最基本的东西,我已经学会了地图,树图和哈希图。最后3次我取得了一些成功,但这一次我不能将它们按降序排列。我从谷歌找到了一些教程,但它们都太复杂了,是的,我可以直接复制它们,让我的代码正常工作,但我更喜欢从中学习。
有什么建议是最清晰的方法吗?因为我以前从来没有使用过地图,所以我现在写这篇文章对他们了解不多。最后,输出应该如下所示:
Output:
Paul : 44,44%
Kelly : 22,22%
Mike : 11,11%发布于 2016-05-06 06:19:26
您可以使用Java 8来完成此操作:
// creating a map with name as key and as value the number of time that name it repeat
Map<String, Long> nameWithVlaues = names.stream()
.collect(Collectors.groupingBy(s -> s,
Collectors.counting()));
// using a stream of de keyset of the precedent map
nameWithVlaues.keySet()
.stream()
// sort the content of this stream using the value contained in the Map
.sorted((val1, val2) -> nameWithVlaues.get(val2).compareTo(nameWithVlaues.get(val1)))
// internal iterator over this stream
.forEachOrdered(name -> {
// getting the percent of ppl with this name
Long percent = (nameWithVlaues.get(name) * 100 / names.size());
// printing it
System.out.println(name + " : " + percent + "%");
});没有注释,它看起来更清晰:D
Map<String, Long> nameWithVlaues = names.stream()
.collect(Collectors.groupingBy(s -> s,
Collectors.counting()));
nameWithVlaues.keySet()
.stream()
.sorted((val1, val2) -> nameWithVlaues.get(val2).compareTo(nameWithVlaues.get(val1)))
.forEachOrdered(name -> {
Long percent = (nameWithVlaues.get(name) * 100 / names.size());
System.out.println(name + " : " + percent + "%");
});发布于 2016-05-06 07:06:06
另一个使用java 8的解决方案可能是这样的:
// creating a new comparator that compare two values by the number of their occurences in the list
Comparator<String> comparatorOfValues = (val1, val2) -> {
Long countVal1 = countIteration(val1, names);
Long countVal2 = countIteration(val2, names);
return - countVal1.compareTo(countVal2);
};
// maping function to write the result like this : NAME : 50%
Function<String, String> mapingFunction = name -> {
return name + " : " + countIteration(name, names) * 100 / names.size() + "%";
};
// applying to names stream the comparator and the maping function and collect result as list
List<String> result2 = names.stream()
.distinct()
.sorted(comparatorOfValues)
.map(mapingFunction)
.collect(Collectors.toList());
result2.forEach(System.out::println);以及计算列表中迭代次数的函数:
// function that count how many values in that collection matching the name
public static Long countIteration(String name, Collection<String> collection) {
return collection.stream()
.filter(val -> name.equals(val))
.count();
}发布于 2016-05-06 08:44:31
有几种方法可以做到这一点。对于初学者,您可以编写以下代码:
HashMap)的哈希表,您可以计算每个名称在列表中出现的次数(每个名称的频率)。{Paul: 4}。完成迭代后,不要忘记从Map中删除此条目。https://stackoverflow.com/questions/37060767
复制相似问题