[英]the quickest way to Implement an algorithm to count how many times each string is present in an array of strings using Java
Just wondering what the quickest way to Implement an algorithm to count how many times each string is present in an array of strings using Java would be? 只是想知道实现一种算法以使用Java计算字符串数组中每个字符串存在多少次的最快方法是什么?
this is what i have tried and it works but im worried it might be "cheating" as it strays away from the question a bit: 这是我尝试过的方法,并且有效,但是我担心它可能会“作弊”,因为它偏离了这个问题:
{
String[] stringArray = {"Random", "Words", "Here","Random", "Words", "Here","Random", "Words", "Here","Random", "Words", "Here"};
List asList = Arrays.asList(stringArray);
Set<String> mySet = new HashSet<>(asList);
mySet.stream().forEach((s) -> {
System.out.println(s + " " +Collections.frequency(asList,s));
});
}
The easiest way is to use Map#merge()
: 最简单的方法是使用
Map#merge()
:
Map<String, Integer> m = new HashMap<>();
for (String s : array)
m.merge(s, 1, Integer::sum);
after that, m
will hold strings as keys and occurrences as values: 之后,
m
将把字符串作为键,将出现的值作为值:
m.forEach((k, v) -> System.out.format("%s occured %s time(s)\n", k, v));
By using Collectors in streams: 通过在流中使用收集器:
Arrays.stream(list).collect(Collectors.groupingBy(e -> e, Collectors.counting()))
So, if you have something like this: 因此,如果您有这样的事情:
String[] list = new String[4];
list[0] = "something";
list[1] = "gfddfgdfg";
list[2] = "something";
list[3] = "somet444hing";
System.out.println(Arrays.stream(list).collect(Collectors.groupingBy(e -> e, Collectors.counting())));
output will be: 输出将是:
{gfddfgdfg=1, something=2, somet444hing=1}
I would use the groupingBy to return a map of counts. 我将使用groupingBy返回计数图。
Map<String, Long> counts = Stream.of(array)
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
to print these as well you can do 也可以打印这些
Stream.of(array)
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + " occurred " + v " times));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.