How is the collect() method used in Java Stream API?

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:

  1. 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());
  1. Collecting to a Set:
Set<String> collectedFruitsSet = fruits.stream()
                                        .collect(Collectors.toSet());
  1. Collecting to a Map:
Map<String, Integer> fruitLengthMap = fruits.stream()
                                             .collect(Collectors.toMap(fruit -> fruit, String::length));
  1. 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.

0 Comments

no data
Be the first to share your comment!