Method reference is used to refer to a method of a functional interface. It is a compact and easy form of a lambda expression. Each time when you are using a lambda expression to just referring a method, you can replace your lambda expression with method reference.
There are following types of method references in java:
Reference to a static method
protected static void methodReferenceWithStaticMethod() { List<String> names = Arrays.asList("Laulau","Kinga","Fusi"); names.forEach(MethodReferenceDemo::printMe); } public static void printMe(String str) { System.out.println("print "+str); }
Reference to an Object method
List<Integer> numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18); numbers = numbers.stream() .sorted((a, b) -> a.compareTo(b)).collect(Collectors.toList()); // equivalent numbers = numbers.stream().sorted(Integer::compareTo).collect(Collectors.toList()); System.out.println(numbers);
Reference with Constructor
class User{ private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { // TODO Auto-generated method stub return this.name; } } .... List<String> names = Arrays.asList("Laulau","Kinga","Fusi"); names.forEach(System.out::println); List<User> users = names.stream().map(User::new).collect(Collectors.toList()); System.out.println(users);
Result
[Laulau, Kinga, Fusi]