I was learning about Streams in Java 8.
For example, If I have to double a number:
Arrays.stream(intArray).map(e->e*2).forEach(System.out::println);
If I have to square a number, then I can use below:
Arrays.stream(intArray).map(e->e*e).forEach(System.out::println);
But If I have to apply both functions on same Integer array using "andThen"
method java.util.function.Function
, I am doing it via:
Function<Integer, Integer> times2 = e -> e * 2;
Function<Integer, Integer> squared = e -> e * e;
Arrays.stream(intArray).map(times2.andThen(squared)).forEach(System.out::println);
Is it possible to rewrite this (3 statements) in single line like :
Arrays.stream(intArray).map(e->e*2.andThen(f->f*f)).forEach(System.out::println);
This is giving me a compiler error. Is it possible to do it?
Looks like Java does not implicitly assume lambda expression of being a specific Functional type. I had to add casting to make it work:
Arrays.stream( new int[]{ 1, 2, 3, 4 } )
.map( ( (IntUnaryOperator)( e -> e*2 ) ).andThen(f->f*f) )
.forEach(System.out::println);
I, personally don't like this and would prefer to use double map calls. I am curious to see a better idea.
If you absolutely must use the .andThen
method, then the other answers here are what you are looking for. But if you are looking for a simple way to combine two functions in a single-line fluent stream operation, then just calling .map
twice is the most readable and compact form that I can think of:
Arrays.stream(intArray).map(e->e*2).map(f->f*f).forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With