Count Specific word on ArrayList

Imagine that you have this situation:

List<String> al = new ArrayList<>();
    al.add("[I] am");
    al.add("you are");
    al.add("I");
    al.add("[I] like java");

Now I want to count the sequence [I] (in this case it will count 2 times). The Link How to count the number of occurrences of an element in a List just pust one word, but on my example I have more than one, i.e, Collections.frequency(al, “[I]”) do not work.

How can I achieve this preferentially using Java 8 ?

Answer

Another way is to split the stream by space and then check whether chunk is equal to [I] e.g.

System.out.println(al.stream().map((w) -> w.split(" ")).flatMap(Arrays::stream).filter((i) ->i.equals("[I]")).count());

Using equals have advantage over contains because let say your list contains words like below

List<String> al = new ArrayList<>();
        al.add("[I] am [I]");
        al.add("you are");
        al.add("I");
        al.add("[I] like java");

This solution will return 3 as expected but the solution mentioned by Bohuslav Burghardt will return 2

Leave a Reply

Your email address will not be published. Required fields are marked *