0

I want to know how to convert lambda expression printing string length to using '::' operation.

String[] arr = new String[]{"1", "234", "56"};
Arrays.stream(arr).forEach(s -> System.out.println(s.length()));
orubt
  • 11
  • 2

1 Answers1

2

Excellent question! Here you could do so twice. Once to map each String to an int by calling length() on each String and a second time by calling println(int) on System.out. Like,

Arrays.stream(arr).mapToInt(String::length).forEach(System.out::println);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • I can get same output when I use map instead of mapToInt. I know that map returns Stream and mapToInt return IntStream. There is any advantage using mapToInt instead of using map? – orubt Aug 11 '21 at 05:39
  • @orubt Yes. Using `map` involves `Integer` (the wrapper type). The primitives types in Java are generally more performant. Why use the `Integer` wrapper when you don't have to? – Elliott Frisch Aug 11 '21 at 12:14