在ArrayList()中找到最常见的String
有没有办法在ArrayList
找到最常见的String
?
ArrayList list = new ArrayList(); list.add("test"); list.add("test"); list.add("hello"); list.add("test");
应该从这个列表中找到“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
方法将列表放在Set的每个元素的Set和循环中。 HTH
编辑/ Java 8 :如果你喜欢使用lambdas的function更强大的Java 8单行解决方案,请尝试:
Map occurrences = list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
在统计中,这称为“模式” 。 vanilla 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);
产量:
test=3
jOOλ是一个支持流上的mode()
的库。 以下程序:
System.out.println( Seq.of("test","test","hello","test") .mode() );
产量:
Optional[test]
(免责声明:我为jOOλ背后的公司工作)
您可以创建HashMap
。 如果字符串已经出现在地图中,则将其键增加1,否则将其添加到地图中。
例如:
put("someValue", 1);
然后,再次假设它是“someValue”,你可以这样做:
put("someValue", get("someValue") + 1);
由于“someValue”的键为1,现在当你把它放入时,键将为2。
之后,您可以轻松浏览地图并提取具有最高价值的密钥 。
我没有写完整的解决方案,尝试构建一个,如果你有问题在另一个问题中发布它。 最佳做法是自学。
我认为最好的方法是使用包含计数的地图。
Map stringsCount = new HashMap<>();
迭代填充此映射的数组:
for(String s: list) { Integer c = stringsCount.get(s); if(c == null) c = new Integer(0); c++; stringsCount.put(s,c); }
最后,您可以获得迭代在地图上的最重复元素:
Map.Entry mostRepeated = null; for(Map.Entry e: stringsCount.entrySet()) { if(mostRepeated == null || mostRepeated.getValue()
并显示最常见的字符串:
if(mostRepeated != null) System.out.println("Most common string: " + mostRepeated.getKey());
根据问题,特别是获取单词,而不是次数(即键的值)。
String mostRepeatedWord = list.stream() .collect(Collectors.groupingBy(w -> w, Collectors.counting())) .entrySet() .stream() .max(Comparator.comparing(Entry::getValue)) .get() .getKey();
您可以使用HashMap
。 循环遍历数组,您可以检查每个String
是否已经是HashMap
的Key,添加它并将值设置为1,如果是,则将其值增加1。
然后你有一个HashMap
其中包含所有唯一的String
和一个相关的数字,表明它们在数组中的数量。
如果有人需要从通常的String []数组中找到最流行的(使用Lists):
public String findPopular (String[] array) { List list = Arrays.asList(array); Map stringsCount = new HashMap(); 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 mostRepeated = null; for(Map.Entry e: stringsCount.entrySet()) { if(mostRepeated == null || mostRepeated.getValue()
- 案件不敏感
我知道这需要更多的时间来实现,但你可以通过在节点中存储count和字符串信息来使用堆数据结构
你可以使用Guava的Multiset:
ArrayList names = ... // count names HashMultiset namesCounts = HashMultiset.create(names); Set> namesAndCounts = namesCounts.entrySet(); // find one most common Multiset.Entry maxNameByCount = Collections.max(namesAndCounts, Comparator.comparing(Multiset.Entry::getCount)); // pick all with the same number of occurrences List mostCommonNames = new ArrayList<>(); for (Multiset.Entry nameAndCount : namesAndCounts) { if (nameAndCount.getCount() == maxNameByCount.getCount()) { mostCommonNames.add(nameAndCount.getElement()); } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map;
public class StringChecker {
public static void main(String[] args) { ArrayList string; string = new ArrayList<>(Arrays.asList("Mah", "Bob", "mah", "bat", "MAh", "BOb")); Map wordMap = new HashMap(); for (String st : string) { String input = st.toUpperCase(); if (wordMap.get(input) != null) { Integer count = wordMap.get(input) + 1; wordMap.put(input, count); } else { wordMap.put(input, 1); } } System.out.println(wordMap); Object maxEntry = Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey(); System.out.println("maxEntry = " + maxEntry);
}
使用此方法,如果ArrayList中有多个最常见的元素,则可以通过将它们添加到新的ArrayList来获取所有这些元素。
public static void main(String[] args) { List words = new ArrayList<>() ; words.add("cat") ; words.add("dog") ; words.add("egg") ; words.add("chair") ; words.add("chair") ; words.add("chair") ; words.add("dog") ; words.add("dog") ; Map count = new HashMap<>() ; for (String word : words) { /* Counts the quantity of each element */ if (! count.containsKey(word)) { count.put(word, 1 ) ; } else { int value = count.get(word) ; value++ ; count.put(word, value) ; } } List mostCommons = new ArrayList<>() ; /* Max elements */ for ( Map.Entry e : count.entrySet() ) { if (e.getValue() == Collections.max(count.values() )){ /* The max value of count */ mostCommons.add(e.getKey()) ; } } System.out.println(mostCommons); } }
HashMaps有很多答案。 我真的不喜欢它们,因为无论如何你必须再次遍历它们。 相反,我会对列表进行排序
Collections.sort(list);
然后循环通过它。 类似的东西
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; } }
应该这样做。