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

前端 未结 2 1596
走了就别回头了
走了就别回头了 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:59

    You can use the frequency method:

    List 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();
    

提交回复
热议问题