One-liner to count number of occurrences of String in a String[] in Java?

前端 未结 2 1562
走了就别回头了
走了就别回头了 2021-02-19 03:59

I have an array of String:

String[] myArray = {\"A\", \"B\", \"B\", \"C\"};

Is there a quick way to count the number of occurrence

相关标签:
2条回答
  • 2021-02-19 04:52

    You can also try using Guava which is full of useful utilities. Using below code, you can count the frequency via Multiset:

    public static void main(final String[] args) {
            String[] myArray = {"A", "B", "B", "C"};
            Multiset<String> wordsMultiset = HashMultiset.create();
            wordsMultiset.addAll(new ArrayList<String>(Arrays.asList(myArray)));
            int counts=wordsMultiset.count("B");
            System.out.println(counts);
        }
    

    Although I know that you are looking for a single liner, but Guava is full of many more utils which are not possible with routine java utils.

    0 讨论(0)
  • 2021-02-19 04:59

    You can use the frequency method:

    List<String> list = Arrays.asList(myArray);
    int count = Collections.frequency(list, "B");
    

    or in one line:

    int count = Collections.frequency(Arrays.asList(myArray), "B");
    

    With Java 8 you can also write:

    long count = Arrays.stream(myArray).filter(s -> "B".equals(s)).count();
    

    Or with a method reference:

    long count = Arrays.stream(myArray).filter("B"::equals).count();
    
    0 讨论(0)
提交回复
热议问题