Java 在 ArrayList() 中找到最常见的 String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22989806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find the most common String in ArrayList()
提问by EspenG
Is there a way to find the most common String
in an ArrayList
?
有没有办法String
在一个中找到最常见的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"]
应该从这个列表中找到“测试”这个词 ["test","test","hello","test"]
采纳答案by VH-NZZ
Don't reinvent the wheel and use the frequency
method of the Collections
class:
不要重新发明轮子并使用类的frequency
方法Collections
:
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)).
返回指定集合中与指定对象相等的元素数。更正式地,返回集合中元素 e 的数量,使得 (o == null ? e == null : o.equals(e))。
If you need to countthe 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
如果您需要计算所有元素的出现次数,请巧妙地使用 Map 和循环 :) 或者将您的列表放入一个 Set 并使用上述frequency
方法在该集合的每个元素上循环。HTH
EDIT / Java 8: If you fancy a more functional, Java 8 one-liner solution with lambdas, try:
编辑/Java 8:如果您喜欢使用 lambda 的功能更强大的 Java 8 单线解决方案,请尝试:
Map<String, Long> occurrences =
list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
回答by Pablo Francisco Pérez Hidalgo
I think the best way to do it is using maps containing counts.
我认为最好的方法是使用包含计数的地图。
Map<String, Integer> stringsCount = new HashMap<>();
And iterate over your array filling this map:
并遍历填充此地图的数组:
for(String s: list)
{
Integer c = stringsCount.get(s);
if(c == null) c = new Integer(0);
c++;
stringsCount.put(s,c);
}
Finally, you can get the most repeated element iterating over the map:
最后,您可以获得在地图上迭代次数最多的元素:
Map.Entry<String,Integer> mostRepeated = null;
for(Map.Entry<String, Integer> e: stringsCount.entrySet())
{
if(mostRepeated == null || mostRepeated.getValue()<e.getValue())
mostRepeated = e;
}
And show the most common string:
并显示最常见的字符串:
if(mostRepeated != null)
System.out.println("Most common string: " + mostRepeated.getKey());
回答by Maroun
You can make a HashMap<String,Integer>
. If the String already appears in the map, increment its keyby one, otherwise, add it to the map.
你可以制作一个HashMap<String,Integer>
. 如果 String 已经出现在地图中,则将其键加一,否则,将其添加到地图中。
For example:
例如:
put("someValue", 1);
Then, assume it's "someValue" again, you can do:
然后,再次假设它是“someValue”,你可以这样做:
put("someValue", get("someValue") + 1);
Since the keyof "someValue" is 1, now when you put it, the key will be 2.
由于“someValue”的key是1,现在放上去的时候key就是2。
After that you can easily go through the map and extract the keythat has the highest value.
之后,您可以轻松浏览地图并提取具有最高值的键。
I didn't write a full solution, try to construct one, if you have problems post it in another question. Best practice is to learn by yourself.
我没有写一个完整的解决方案,尝试构建一个,如果你有问题,请在另一个问题中发布。最好的做法是自学。
回答by LionC
You could use a HashMap<String,Integer>
. Looping through the array, you can check for each String
if it is not already a Key of your HashMap
, add it and set the value to 1, if it is, increase its value by 1.
你可以使用一个HashMap<String,Integer>
. 循环遍历数组,您可以检查每个String
是否还不是您的 Key HashMap
,添加它并将值设置为 1,如果是,则将其值增加 1。
Then you have a HashMap
with all unique String
s and an associated number stating their amount in the array.
然后你有一个HashMap
所有唯一的String
s 和一个相关的数字,说明它们在数组中的数量。
回答by Bex
There are a lot of answers suggesting HashMaps. I really don't like them, because you have to iterate through them once again anyway. Rather, I would sort the List
有很多答案建议使用 HashMaps。我真的不喜欢它们,因为无论如何你必须再次遍历它们。相反,我会对列表进行排序
Collections.sort(list);
and then loop through it. Something similar to
然后循环遍历它。类似的东西
String prev = null, mostCommon=null;
int num = 0, max = 0;
for (String str:list) {
if (str.equals(prev)) {
num++;
} else {
if (num>max) {
max = num;
mostCommon = str;
}
num = 1;
prev = str;
}
}
should do it.
应该这样做。
回答by Максим Скрипченко
If somebody need to find most popular from usual String[] array (using Lists):
如果有人需要从通常的 String[] 数组中找到最流行的(使用列表):
public String findPopular (String[] array) {
List<String> list = Arrays.asList(array);
Map<String, Integer> stringsCount = new HashMap<String, Integer>();
for(String string: list)
{
if (string.length() > 0) {
string = string.toLowerCase();
Integer count = stringsCount.get(string);
if(count == null) count = new Integer(0);
count++;
stringsCount.put(string,count);
}
}
Map.Entry<String,Integer> mostRepeated = null;
for(Map.Entry<String, Integer> e: stringsCount.entrySet())
{
if(mostRepeated == null || mostRepeated.getValue()<e.getValue())
mostRepeated = e;
}
try {
return mostRepeated.getKey();
} catch (NullPointerException e) {
System.out.println("Cannot find most popular value at the List. Maybe all strings are empty");
return "";
}
}
- case non-sensitive
- 不区分大小写
回答by Lukas Eder
In statistics, this is called the "mode". A vanilla Java 8 solution looks like this:
在统计学中,这被称为“模式”。一个普通的 Java 8 解决方案如下所示:
Stream.of("test","test","hello","test")
.collect(Collectors.groupingBy(s -> s, Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))
.ifPresent(System.out::println);
Which yields:
其中产生:
test=3
jOOλis a library that supports mode()
on streams. The following program:
System.out.println(
Seq.of("test","test","hello","test")
.mode()
);
Yields:
产量:
Optional[test]
(disclaimer: I work for the company behind jOOλ)
(免责声明:我为 jOOλ 背后的公司工作)
回答by fatih tekin
i know this takes more time to implement but you can use heap data structure by storing in the nodes the count and the string information
我知道这需要更多时间来实现,但您可以通过在节点中存储计数和字符串信息来使用堆数据结构
回答by ChandraBhan Singh
As per question, Specifically just to get word, not the number of times (i.e. value of key).
根据问题,特别是为了获得单词,而不是次数(即键的值)。
String mostRepeatedWord
= list.stream()
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))
.get()
.getKey();
回答by manicka
You can use Guava's Multiset:
您可以使用 Guava 的 Multiset:
ArrayList<String> names = ...
// count names
HashMultiset<String> namesCounts = HashMultiset.create(names);
Set<Multiset.Entry<String>> namesAndCounts = namesCounts.entrySet();
// find one most common
Multiset.Entry<String> maxNameByCount = Collections.max(namesAndCounts, Comparator.comparing(Multiset.Entry::getCount));
// pick all with the same number of occurrences
List<String> mostCommonNames = new ArrayList<>();
for (Multiset.Entry<String> nameAndCount : namesAndCounts) {
if (nameAndCount.getCount() == maxNameByCount.getCount()) {
mostCommonNames.add(nameAndCount.getElement());
}
}