我的输入是n个字符串。我想获得唯一值,以及这些字符串不区分大小写的出现次数。
我想到了在数组中获取输入;对它进行排序并进行循环来计算出现率。还有其他方法吗?
答案 0 :(得分:2)
您可以使用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}
答案 1 :(得分:1)
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;
}
这将返回一个地图,其中的键是唯一的单词,每个值都会告诉你它出现了多少次。