Search code examples
lambdajava-8

Java Lambda Expression: How to count elements in List


List<String> l1 = Arrays.asList("ab", "cd", "ef");
     long count = l1.stream().count();
     System.out.println(count);

I want to use lambda expression instead of count() method. How can I do that.


Solution

  • You could do this via a stream by mapping each string in the input list to the integer 1, then use Collectors.summingInt to tally the 1 counts at the end.

    List<String> l1 = Arrays.asList("ab", "cd", "ef");
    int length = l1.stream().map(x -> 1).collect(Collectors.summingInt(Integer::intValue));
    System.out.println(length);  // 3