I wrote a simple program to iterate through Listusing 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);
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.print(t + " ");
}
});
System.out.println(" ");
list.forEach((Integer t) -> System.out.print(t + " "));
System.out.println(" ");
list.forEach((t) -> System.out.print(t + " "));
System.out.println(" ");
list.forEach(System.out::print);
}
}
In the program below, I have more than two pieces of logic to execute inside a lambda. The problem I am facing is how to update the 4th method, 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);
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.print(t + " Twice is : ");
System.out.print(t*2 + " , ");
}
});
System.out.println(" ");
list.forEach((Integer t) ->
{System.out.print(t + " Twice is : ");
System.out.print(t*2 + " , ");
});
System.out.println(" ");
list.forEach((t) -> {System.out.print(t + " Twice is : ");
System.out.print(t*2 + " , ");
});
}
}
source
share