在 java 中使用哪个集合查找特定字符串重复多少次的最佳方法?



大小为 100 的字符串数组,例如:{'Hemant','Mahesh','ABC'...} 1.要求:查找字符串计数,找到特定字符串的次数是多少? 例如:赫曼特 2 |马赫什 5 2.哪个集合最适合实现相同?如何实施?

你可以按如下方式使用stream

Map<String, Integer> countMap = Arrays.stream(split)
.collect(toMap(Function.identity(), v -> 1, Integer::sum));

在这里,首先将 Array 转换为流(您也可以使用Stream.of(array)(,然后使用 Function.identity(( 和初始值收集每个键到 1 (v->1(,如果键已经存在,则递增 1。toMapCollectors.toMap的静态导入

希望对您有所帮助。

Stream.of(stringArray)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting())) // A map of the strings with their count
.entrySet().stream()
.forEach(e -> System.out.printf("%20s : %d%n", e.getKey(), e.getValue()));

这使用流来创建字符串到其频率的映射。

最新更新