Practical Usage Patterns
Stream Processing with Method References
Method references shine in stream processing scenarios, providing clean and concise code transformations.
Filtering Examples
public class StreamMethodReferences {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Filtering with method reference
List<String> longNames = names.stream()
.filter(name -> name.length() > 4)
.collect(Collectors.toList());
// Equivalent method reference
List<String> filteredNames = names.stream()
.filter(StringUtils::isNotBlank)
.collect(Collectors.toList());
}
}
Sorting and Comparator Usage
graph LR
A[Method References] --> B[Sorting]
A --> C[Comparator]
B --> D[Natural Ordering]
B --> E[Custom Ordering]
Sorting Techniques
public class SortingDemo {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
// Sort by name
people.sort(Comparator.comparing(Person::getName));
// Sort by age
people.sort(Comparator.comparing(Person::getAge));
}
}
class Person {
private String name;
private int age;
// Constructor, getters
}
Functional Interface Mapping
Functional Interface |
Method Reference Pattern |
Example |
Predicate |
ClassName::methodReturningBoolean |
String::isEmpty |
Function |
ClassName::transformMethod |
Integer::toString |
Consumer |
System.out::println |
Logging operations |
Collection Manipulation
public class CollectionMethodReferences {
public static void main(String[] args) {
List<String> words = Arrays.asList("Java", "Python", "JavaScript");
// Converting to uppercase
List<String> upperWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Creating new instances
List<StringBuilder> builders = words.stream()
.map(StringBuilder::new)
.collect(Collectors.toList());
}
}
Advanced Method Reference Patterns
Constructor Chaining
public class ConstructorMethodReference {
public static void main(String[] args) {
// Creating multiple instances
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Person> people = names.stream()
.map(Person::new)
.collect(Collectors.toList());
}
}
- Method references are generally more performant than lambda expressions
- Minimal overhead compared to direct method calls
- Recommended for complex transformations
Best Practices
- Use method references for clear, single-method transformations
- Prefer method references over verbose lambda expressions
- Ensure method signatures match functional interfaces
At LabEx, we encourage developers to master method references as a powerful Java functional programming technique.