Java 字符串数组最大最小唯一出现
Java String Array max min unique occurrence
我的输入是 n 个字符串。我想获得唯一值,以及这些不区分大小写的字符串的出现次数。
我想到了获取数组中的输入;对其进行排序并进行循环以计算出现次数。还有别的办法吗?
public Map<String, Integer> calculateOccurences(Collection<String> collectionOfStrings) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (String string : collectionOfStrings) {
String stringAsLowerCase = string.toLowerCase();
Integer integer = map.get(stringAsLowerCase);
if (integer == null) { //this has never been added
map.put(stringAsLowerCase, 1);
} else {
map.put(stringAsLowerCase, integer + 1);
}
}
return map;
}
这将 return 一个地图,其中的键是唯一的单词,每个值都会告诉您它出现了多少次。
您可以使用 Stream api 工具来获得您想要的内容:
List<String> list = Arrays.asList("hello","world","Hola","Mundo","hello", "world","Hola","Mundo","mundo","Hello","Hola","mundo","Mundo");
Map<String, Long> ocurrences = list
.stream()
.map(String::toLowerCase) // make case insensitive
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(ocurrences);
输出:
{world=2, mundo=5, hello=3, hola=3}
我的输入是 n 个字符串。我想获得唯一值,以及这些不区分大小写的字符串的出现次数。
我想到了获取数组中的输入;对其进行排序并进行循环以计算出现次数。还有别的办法吗?
public Map<String, Integer> calculateOccurences(Collection<String> collectionOfStrings) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (String string : collectionOfStrings) {
String stringAsLowerCase = string.toLowerCase();
Integer integer = map.get(stringAsLowerCase);
if (integer == null) { //this has never been added
map.put(stringAsLowerCase, 1);
} else {
map.put(stringAsLowerCase, integer + 1);
}
}
return map;
}
这将 return 一个地图,其中的键是唯一的单词,每个值都会告诉您它出现了多少次。
您可以使用 Stream api 工具来获得您想要的内容:
List<String> list = Arrays.asList("hello","world","Hola","Mundo","hello", "world","Hola","Mundo","mundo","Hello","Hola","mundo","Mundo");
Map<String, Long> ocurrences = list
.stream()
.map(String::toLowerCase) // make case insensitive
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(ocurrences);
输出:
{world=2, mundo=5, hello=3, hola=3}