Math.toIntExact inside lambda expression?

  • A+

I'm learning about lambda expressions. Given a list of names, I want to count the numbers of names that start with N.

I did that:

final static List<String> friends = Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");  public static int countFriendsStartWithN() {     return  Math.toIntExact(friends             .stream()             .filter(name -> name.startsWith("N"))             .count()); } 

The call to the count method returns a primitive long but I want an int.
I used Math.toIntExact to get the long value as int.

Is it possible to get the int value directly inside the lambda expression?


No, it is not possible to fit your call to toIntExact into your chain of method calls, your stream pipeline. This is because count is a terminal operation and returns a primitive long on which no method call is possible. A terminal operation is an operation that ends the stream pipeline and produces a result (or a side effect).

So I believe the best thing you can do is to live with the code you already have. IMHO it’s fine.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: