The collect() method in the Java Stream API is used to accumulate the elements of a stream into a collection or another data structure. It is a terminal operation that transforms the elements of the stream into a different form, such as a List, Set, Map, or even a single value.
The collect() method takes a Collector as an argument, which defines how the elements should be collected. Here are some common examples of using the collect() method:
- Collecting to a List:
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
List<String> collectedFruits = fruits.stream()
.filter(fruit -> fruit.startsWith("A"))
.collect(Collectors.toList());
- Collecting to a Set:
Set<String> collectedFruitsSet = fruits.stream()
.collect(Collectors.toSet());
- Collecting to a Map:
Map<String, Integer> fruitLengthMap = fruits.stream()
.collect(Collectors.toMap(fruit -> fruit, String::length));
- Joining Strings:
String joinedFruits = fruits.stream()
.collect(Collectors.joining(", "));
In these examples, the collect() method is used to gather the results of the stream operations into different types of collections or formats, making it a powerful tool for data processing in Java.
