Functional Interfaces and Streams in Java 8
Overview of Streams
Streams are a new abstraction introduced in Java 8 that allow for functional-style operations on collections of elements. They provide a way to process sequences of elements (like lists or sets) in a declarative manner.
Using Functional Interfaces with Streams
Functional interfaces play a crucial role in the Stream API, as they are used to define the behavior of operations such as filtering, mapping, and reducing.
1. Using Predicate
with Streams
The filter()
method uses a Predicate
to determine which elements to include in the resulting stream.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
System.out.println(filteredNames); // Output: [Alice]
2. Using Function
with Streams
The map()
method applies a function to each element in the stream, transforming it into another form.
List<Integer> lengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths); // Output: [5, 3, 7, 5]
3. Using Consumer
with Streams
The forEach()
method takes a consumer that defines what to do with each element in the stream.
names.stream()
.forEach(name -> System.out.println(name)); // Prints each name
4. Using Supplier
with Streams
A supplier can be used to provide initial values for operations like collecting results.
Supplier<List<String>> listSupplier = ArrayList::new;
List<String> collectedNames = names.stream()
.filter(name -> name.length() > 3)
.collect(listSupplier, List::add, List::addAll);
System.out.println(collectedNames); // Output: [Alice, Charlie]
5. Using BinarayOperator
with Streams
The reduce()
method uses a binary operator to combine elements into a single result.
Optional<Integer> totalLength = names.stream()
.map(String::length)
.reduce(0, Integer::sum);
System.out.println(totalLength.get()); // Output: 20
Conclusion
The integration of functional interfaces with the Stream API allows developers to write clean and efficient code for processing collections. By leveraging predicates, functions, consumers, suppliers, and binary operators, you can perform complex data manipulations with ease.
Top comments (0)