Home > Enterprise >  Combine two lambda expressions without intermediate step
Combine two lambda expressions without intermediate step

Time:06-30

I'm trying to write a lambda expression that sorts a string array by string length by using a single lambda expression variable. This is what I have come up with (using two)

public static void main(String[] args) {

    Consumer<String[]> sort =  s -> Arrays.sort(s, (String s1, String s2) -> s1.length() - s2.length());

    Consumer<String[]> print = sort.andThen(s -> System.out.println(Arrays.toString(s)));

    print.accept(strings);

}

Is there a way to combine sort and print so that they are just one expression? I have tried this:

Consumer<String[]> print = (s -> Arrays.sort(s, (String s1, String s2) -> s1.length() - s2.length())).andThen(s -> System.out.println(Arrays.toString(s)));

But I'm just getting

String s1, String s2) -> s1.length() - s2.length()

marked red saying "Cannot infer functional interface type". Is what I'm trying even possible? I know it's a pretty useless this worrying about but now I'm curious if this is possible.

CodePudding user response:

Lambdas in Java always need to target a functional interface (an interface with only a single abstract method). In your case, that is the Consumer-interface.

The reason you get the error when you chain the two lambdas together with andThen is because the compiler doesn't know which functional interface the first lambda is targetting. So it doesn't know which andThen function to call. It only knows that the whole expression should result in a Consumer.

To fix it, you would need to cast the first lambda to Consumer<String[]>. Like this:

Consumer<String[]> print = ((Consumer<String[]>) s -> Arrays.sort(s, (String s1, String s2) -> s1.length() - s2.length()))
    .andThen(s -> System.out.println(Arrays.toString(s)));

CodePudding user response:

This can be done using :

        Arrays.stream(s).sorted(Comparator.comparingInt(String::length))
            .forEach(System.out::println);
  • Related