Java字符串数组最大最小唯一出现次数
我的输入是n个字符串。我想得到唯一的值,以及这些字符串不区分大小写的出现次数 我有一个在数组中获取输入的想法;对其进行排序并进行循环以计算发生率。还有别的办法吗Java字符串数组最大最小唯一出现次数,java,arrays,string,unique,instances,Java,Arrays,String,Unique,Instances,我的输入是n个字符串。我想得到唯一的值,以及这些字符串不区分大小写的出现次数 我有一个在数组中获取输入的想法;对其进行排序并进行循环以计算发生率。还有别的办法吗 公共地图计算发生率(集合字符串){ public Map<String, Integer> calculateOccurences(Collection<String> collectionOfStrings) { HashMap<String, Integer> map = new
公共地图计算发生率(集合字符串){
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;
}
HashMap=newHashMap();
用于(字符串:collectionOfStrings){
String stringAsLowerCase=String.toLowerCase();
整数=map.get(stringAsLowerCase);
如果(integer==null){//,则从未添加此值
map.put(stringAsLowerCase,1);
}否则{
map.put(stringAsLowerCase,整数+1);
}
}
返回图;
}
这将返回一个映射,其中键是唯一的单词,每个值都将告诉您它出现了多少次。您可以使用流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);
List List=Arrays.asList(“hello”、“world”、“Hola”、“Mundo”、“hello”、“world”、“Hola”、“Mundo”、“Mundo”、“hello”、“Hola”、“Mundo”、“Mundo”);
映射眼率=列表
.stream()
.map(String::toLowerCase)//不区分大小写
.collect(Collectors.groupingBy(Function.identity()、Collectors.counting());
系统输出打印LN(眼病);
输出:
{world=2,mundo=5,hello=3,hola=3}
您的输入(n个字符串)是什么样子的?它是数组、列表还是地图?或者其他任何东西?将字符串映射到出现的次数。它是一个stringsbook数组;玻璃;电话;观察;可移动的墨水笔;观察;玻璃;使用
Integer=map.getOrDefault(stringAsLowerCase,0)代码>然后您可以摆脱条件逻辑