Swi*_*ipi 1 java string list java-stream
我有一个带有字符串的列表并将相同的字符串分组。
List<String> allTypes = new ArrayList<String>();
Map<String, Long> count = allTypes.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)
然后我得到最频繁的字符串的计数
Long max = Collections.max(count.values());
Run Code Online (Sandbox Code Playgroud)
现在我不想要最频繁的字符串的计数,我也想要关联的字符串。该列表随机填充了来自其他列表的字符串。
我认为您正在寻找:
Optional<Map.Entry<String, Long>> maxEntryByValue = count.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)
或者如果你想要它没有Optional,你可以使用:
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(..)
Run Code Online (Sandbox Code Playgroud)