Instead using:
public class RunnableTest { public static void main(String[] args) { System.out.println("=== RunnableTest ==="); Runnable r = new Runnable(){ @Override public void run(){ System.out.println("Hello world one!"); } }; r.run(); } }
Use:
public class RunnableTest { public static void main(String[] args) { System.out.println("=== RunnableTest ==="); Runnable r = () -> System.out.println("Hello world two!"); r.run(); } }
Java Way
public class ListenerTest { public static void main(String[] args) { JButton testButton = new JButton("Test Button"); testButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae){ System.out.println("Click Detected by Anon Class"); } }); // Swing stuff JFrame frame = new JFrame("Listener Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(testButton, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
Lambda Way
public class ListenerTest { public static void main(String[] args) { JButton testButton = new JButton("Test Button"); testButton.addActionListener(e -> System.out.println("Click Detected by Lambda Listner")); // Swing stuff JFrame frame = new JFrame("Listener Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(testButton, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
Java Way
public class Person { new Thread(new Runnable() { @Override public void run() { System.out.println("Hello from thread"); } }).start();
Lambda Way
new Thread( () -> System.out.println("Hello from thread") ).start();
Define:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Java Way
for(Integer n: list) { System.out.println(n); }
Lambda Way
list.forEach(n -> System.out.println(n));
Java8 Way
list.forEach(System.out::println);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Java Way
for(Integer n : list) { int x = n * n; System.out.println(x); }
Lambda Way
list.stream().map((x) -> x*x).forEach(System.out::println);