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

问题描述 投票:0回答:3

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

java
3个回答
1
投票

您可以使用的另一种方法是HashSet。哈希集将仅在数组中保留唯一值,然后您可以使用Collections.frequency(Collection c, Object o)

检查这些值在数组中出现多少次

代码:

String[] testStrings = { "Test", "Test", "Stackoverflow", "is", "not", "Stackoverflow", "error", "Test" };
HashSet<String> hashSet = new HashSet<>(Arrays.asList(testStrings));
for (String testString : hashSet) {
    System.out.println(testString + ":" + Collections.frequency(Arrays.asList(testStrings), testString));
}

输出:

not:1
Test:3
is:1
error:1
Stackoverflow:2

1
投票
 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()));

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


0
投票

您可以如下使用stream

Map<String, Integer> countMap = Arrays.stream(split)
.collect(toMap(Function.identity(), v -> 1, Integer::sum));
© www.soinside.com 2019 - 2024. All rights reserved.