Lambda and Anonymous function Java

Lambda Function and Anonymous function

Defination

A more concise way to represent anonymous classes that implement certain interfaces

Grammar

1
(Parameters) ->{Code Block}

eg:

without para

1
() -> System.out.println("Hello, World!")

With one para

1
x -> System.out.println(x)

with more para

1
(x, y) -> x + y

combine with the function

1
2
Runnable run = () -> System.out.println("Running...");
new Thread(run).start();

Anonymous function

Defination

An unnamed function

Often used for brief, one-time operations

Compare beteween Lambda and Anonymous Function

lambda

1
2
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
Collections.sort(names, (a, b) -> a.compareTo(b));

anonymous function

1
2
3
4
5
6
7
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.compareTo(b);
}
});