如何检查ArrayList中的元素是否等于某个值?

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

我有一个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();
android android-studio arraylist switch-statement
1个回答
0
投票

您能尝试这个吗?

        Map<String, Long> counted = list1.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(counted);
© www.soinside.com 2019 - 2024. All rights reserved.