sauumum sauumum - 4 months ago 15
Java Question

Java 8: Lambda expression contains more than one statement/logic

I wrote a simple program to iterate through a list using java 8 lambda.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class FirstLamdaExpression {

public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//Way 1 : old way
list.forEach(new Consumer<Integer>() {

@Override
public void accept(Integer t) {
System.out.print(t + " ");

}
});

//Way 2
System.out.println(" ");
list.forEach((Integer t) -> System.out.print(t + " "));

//Way 3
System.out.println(" ");
list.forEach((t) -> System.out.print(t + " "));

//Way 4
System.out.println(" ");
list.forEach(System.out::print);

}

}


In below program I have more than 2 logic to perform inside lambda. The problem I am facing is how to update the 4th way i.e.
System.out::print
?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class SecondLamdaExpression {

public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//Way 1 : Old way
list.forEach(new Consumer<Integer>() {

@Override
public void accept(Integer t) {
System.out.print(t + " Twice is : ");
System.out.print(t*2 + " , ");

}
});

//Way 2
System.out.println(" ");
list.forEach((Integer t) ->
{System.out.print(t + " Twice is : ");
System.out.print(t*2 + " , ");
});

//Way 3
System.out.println(" ");
list.forEach((t) -> {System.out.print(t + " Twice is : ");
System.out.print(t*2 + " , ");
});

//Way 4
//System.out.println(" ");
//list.forEach((t)-> System.out::print{(t + " Twice is : ");});

}

}

Answer

It seems you are asking how to pass t + " Twice is : " + t*2 + " , " to a method reference. You can't pass explicit parameters to method references, and you can't combine method references with lambda expressions.

You could use a Stream pipeline to first map t whatever you wish to print for each value of t, and than use a forEach with method reference to print it :

list.stream().map(t -> t + "  Twice is : " + t*2 + "  , ").forEach(System.out::print);
Comments