Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite the algorithm in java stream with less effort?

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?

like image 772
Nicky Avatar asked Jun 04 '17 16:06

Nicky


2 Answers

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.

like image 86
tsolakp Avatar answered Oct 26 '22 11:10

tsolakp


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);
like image 30
Matt Leidholm Avatar answered Oct 26 '22 10:10

Matt Leidholm