英文:
Java ArrayList same string grouping and get most frequent String
问题
我有一个包含字符串的列表,并且将相同的字符串分组。
List<String> allTypes = new ArrayList<String>();
Map<String, Long> count = allTypes.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
然后,我获取出现频率最高的字符串的计数。
Long max = Collections.max(count.values());
现在,我不仅想要出现频率最高的字符串的计数,还想要关联的字符串。该列表是随机填充的,其中的字符串来自另一个列表。
英文:
i have a List with Strings and group the same Strings.
List<String> allTypes = new ArrayList<String>();
Map<String, Long> count = allTypes.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
and then i get the count of the most frequent String
Long max = Collections.max(count.values());
Now i dont want only the count of the most frequent String i want the
associated String too. The List is randomly filled with Strings from a other List.
答案1
得分: 5
我认为你正在寻找:
使用Optional
的版本:
Optional<Map.Entry<String, Long>> maxEntryByValue = count.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue));
如果你想要不使用Optional
,可以使用以下版本:
Map.Entry<String, Long> maxEntryByValue = count.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue))
.orElse(null); // 或任何默认值,或者你可以使用 orElseThrow(..)
英文:
I think you are looking to:
Optional<Map.Entry<String, Long>> maxEntryByValue = count.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue));
Or if you want it without Optional
, you can use:
Map.Entry<String, Long> maxEntryByValue = count.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue))
.orElse(null); // or any default value, or you can use orElseThrow(..)
答案2
得分: 0
你可以遍历这些条目,如果value与你的targetValue相匹配,就将该键存储在Set<K> keys
中。这将包含所有具有特定targetValue的键。
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value.equals(targetValue)) {
keys.add(entry.getKey());//将键添加到set<K> keys中
}
}
return keys; //所有具有相同targetValue的键将在此集合中
英文:
You can iterate over the entries and if the value matches your targetValue then store that key in the Set<K> keys
. This will contain all the keys having that particular targetValue
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value.equals(targetValue)) {
keys.add(entry.getKey());//add the keys to the set<K> keys
}
}
return keys; //all the keys having the same targetValue will be in this set
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论