Rewrite the algorithm in java stream with less effort?

Viewed 253

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?

3 Answers
Related