我有一个ArrayList list1,其中包含以下值:{“ A”,“ A”,“ A”,“ B”,“ B”,“ A”,“ C”,“ C”,“ B”, “ B”,“ B”}。
我想计算列表1中每个字母(A,B和C)重复多少次。
我已完成以下操作,但结果为0。
for (i=0; i<=list1.size(); i++) {
switch (list1.get(i)) {
case "A":
LetterA = LetterA + 1;
case "B":
LetterB = LetterB + 1;
case "C":
LetterC = LetterC + 1;
}
}
Toast.makeText(getApplicationContext(), "Letter A repeats: " + LetterA + " times" + "\nLetter B repeats: " + LetterB + " times" +
"\nLetterC repeats: " + LetterC + " times", Toast.LENGTH_LONG).show();
您能尝试这个吗?
Map<String, Long> counted = list1.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counted);