Table of Contents

Java8 Lambda Use cases

Runnable

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();
 
  }
}

Listener

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);
 
  }
}

Improve Code

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();

Foreach

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);

Foreach and Multiply

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);

MapReduce in java

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

Java Way

int sum = 0;
for(Integer n : list) {
    int x = n * n;
    sum = sum + x;
}
System.out.println(sum);

Lambda Way

int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get();
System.out.println(sum);