Java

ラムダ式 #2

Lambda Expressionとは??

  • using Anonymous class
    dispbutton.addActionListener(new ActionListener() { // Using Anonymous Class 
        public void actionPerformed(ActionEvent e) {
            contents.setText("Hello World! - By Anonymous Class"); }
    }); // Using Anonymous Class
    add(dispbutton); //AddthebuttonobjecttothisFrame
  • using Lambda expression
dispbutton.addActionListener(e -> contents.setText("Hellow World! - By Lambda Expression"));
add(dispbutton); //AddthebuttonobjecttothisFrame

文法

Event Listener

Anonymous class
...
button1 = new JButton("foobar");
button1.addActionListener(this); 
...
public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == button1) {
    //do something 
    }
...
}
...
Lambda expression
...
button1 = new JButton("foobar");
button1.addActionListener(e -> button1Click()); 
...
public void button1Click() { 
    //do something
}

Thread run method

Anonymous class
Runnable runner = new Runnable() { 
    @Override
    public void run() {
    System.out.println("example"); 
    }
}; 
runner.run();
Lambda expression
Runnable runner = () -> { System.out.println("example"); }; 
runner.run();

Collection method

Anonymous class
List<Integer> list = Arrays.asList(1, 3, 2); 
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2); }
}
);
Lambda expression
List<Integer> list = Arrays.asList(1, 3, 2); 
Collections.sort(list, (o1, o2) -> Integer.compare(o1, o2));