Understanding Method References in Java
Method references allow you to reuse existing methods as implementations for functional enterface abstract methods.
Key Characteristics
- Requires a functional interface context
- Reefrenced method must already exist
- Parameter types and return type must match the abstract method
- Referenced method functionality should satisfy current requirements
Types of Method References
1. Static Method References
Format: ClassName::staticMethod
Example: Integer::parseInt
List<String> numbers = Arrays.asList("1", "2", "3", "4", "5");
numbers.stream()
.map(Integer::valueOf)
.forEach(System.out::println);
2. Instance Method References
Format: object::instanceMethod
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream()
.filter(new StringValidator()::isValidName)
.forEach(System.out::println);
3. Constructor References
Format: ClassName::new
List<String> studentData = Arrays.asList("John,20", "Jane,19");
List<Student> students = studentData.stream()
.map(Student::new)
.collect(Collectors.toList());
4. Special Cases
Format: ClassName::instanceMethod (for arbitrary objects)
List<String> words = Arrays.asList("hello", "world");
words.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
Array constructor reference:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Integer[] array = numbers.stream()
.toArray(Integer[]::new);