Home > Mobile >  How to count a given char in LinkedList in java
How to count a given char in LinkedList in java

Time:11-02

When I create a LinkedList and add some values like this:

List<String> l = new LinkedList<>();
l.add("I");
l.add("have");
l.add("eaten");
l.add("!");

How to count the occurrence of char "e" using lambda or other method?

CodePudding user response:

Stream the contents of the List. Map each value to an int by replacing all non-'e' values with nothing and taking the length of the resulting String. Take the sum() of all such lengths. Like,

int count = l.stream().mapToInt(s -> s.replaceAll("[^e]", "").length()).sum();
  • Related