Rewrite algorithm to java stream with less effort?

I found out about threads in Java 8.

For example, if I need to double a number:

Arrays.stream(intArray).map(e->e*2).forEach(System.out::println);

If I need a square number, I can use below:

Arrays.stream(intArray).map(e->e*e).forEach(System.out::println);

But if I need to apply both functions in the same Integer array using the method "andThen" java.util.function.Function, I do this through:

  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 operators) in one line as follows:

Arrays.stream(intArray).map(e->e*2.andThen(f->f*f)).forEach(System.out::println);

This gives me a compiler error. Can this be done?

+4
source share
3 answers

Java does not seem to imply that the lambda expression is 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);

, . .

+4

.andThen, - , . , .map - , :

Arrays.stream(intArray).map(e->e*2).map(f->f*f).forEach(System.out::println);
+3

@tsolakp answer , , .


:

Arrays.stream(intArray)
    .boxed()
    .map(e -> e * 2.andThen(e -> e * e)) // wrong! does not compile!
    .forEach(System.out::println);

, Java lambdas , . , SAM ( ). SAM , , . : Function, Predicate, Consumer, Supplier, Runnable .., SAM, , :

@FunctionalInterface
public interface Whatever<T, R> {

    R thisIsMySingleAbstractMethod(T argument);
}

-, Whatever, :

Whatever<Integer, String> whatever = number -> number.toString();

Function<Integer, String>:

Function<Integer, String> whatever = number -> number.toString();

, lambdas , SAM. .

map a Function . ​​ , map. ( ) , lambda .

, - ( andThen ), , .

-: , .

+2

Source: https://habr.com/ru/post/1678504/


All Articles