查找ArrayList中最常见的字符串() [英] Find the most common String in ArrayList()
问题描述
不知道是否有找到最常见的字符串的方式
在的ArrayList
。
的ArrayList<串GT;名单=新的ArrayList<>();
list.add(测试);
list.add(测试);
list.add(你好);
list.add(测试);
那么,有没有从该名单中查找单词测试的方式 [测试,测试,你好,测试]
<? / p>
不要重新发明轮子,并使用频率
的集合的方法
类:
公共静态INT频率(收集&LT;&GT; C,对象o)
返回指定集合等于元件的数目
指定的对象。更正式地说,返回的元素e的数量
集合中满足(o == NULLË== NULL:o.equals(e)项)。
块引用>如果你需要的计数的事故为所有元素,使用地图和循环巧妙:)
或把你在设置列表和循环用频率以上
方法中的每个元素。 HTH编辑/ Java的8 :如果你喜欢用lambda表达式一个功能更强大,爪哇8单行的解决方案,请尝试:
地图&LT;弦乐,朗GT&;事件=
list.stream()收集。(Collectors.groupingBy(W - &GT; W,Collectors.counting()));Wonder if there is an way to find the most common
String
in aArrayList
.ArrayList<String> list = new ArrayList<>(); list.add("test"); list.add("test"); list.add("hello"); list.add("test");
So is there an way to find the word "test" from this list
["test","test","hello","test"]
?解决方案Don't reinvent the wheel and use the
frequency
method of theCollections
class:public static int frequency(Collection<?> c, Object o)
Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).
If you need to count the occurrences for all elements, use a Map and loop cleverly :) Or put your list in a Set and loop on each element of the set with the
frequency
method above. HTHEDIT / Java 8: If you fancy a more functional, Java 8 one-liner solution with lambdas, try:
Map<String, Long> occurrences = list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
这篇关于查找ArrayList中最常见的字符串()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!