在 ArrayList() 中找到最常见的 String [英] Find the most common String in ArrayList()
问题描述
有没有办法在ArrayList
中找到最常见的String
?
ArrayListlist = new ArrayList<>();list.add("测试");list.add("测试");list.add("你好");list.add("测试");
应该从这个列表中找到单词test"["test","test","hello","test"]
不要重新发明轮子,使用 Collections
类的 frequency
方法:
public static int frequency(Collection>c, Object o)
<块引用>
返回指定集合中元素的个数等于指定的对象.更正式地,返回元素数 e在集合中使得 (o == null ? e == null : o.equals(e)).
如果您需要计算所有元素的出现次数,请使用 Map 并巧妙地循环:)或者将您的列表放入一个集合中,并使用上面的 frequency
方法在集合的每个元素上循环.HTH
编辑/Java 8:如果您喜欢使用 lambda 表达式的功能更强大的 Java 8 单行解决方案,请尝试:
Map出现次数 =list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
Is there a way to find the most common String
in an ArrayList
?
ArrayList<String> list = new ArrayList<>();
list.add("test");
list.add("test");
list.add("hello");
list.add("test");
Should find the word "test" from this list ["test","test","hello","test"]
Don't reinvent the wheel and use the frequency
method of the Collections
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. HTH
EDIT / 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() 中找到最常见的 String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!