In Java, collecting elements with Streams involves using the Stream API to process a sequence of elements and gather the results into a collection or other data structure. The collect method is key, often paired with Collectors to define how elements are accumulated.
Syntax
Stream<T> stream = collection.stream();
// Collect to a result
R result = stream.collect(Collectors.someCollector());
Code language: JavaScript (javascript)
Common Examples
Collect to a List
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
// Result: [Alice]
Code language: JavaScript (javascript)
Collect to a Set
List<String> names = Arrays.asList("Alice", "Bob", "Alice");
Set<String> uniqueNames = names.stream()
.collect(Collectors.toSet());
// Result: [Alice, Bob] (duplicates removed)
Code language: JavaScript (javascript)
Collect to a Map
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Map<String, Integer> nameLengthMap = names.stream()
.collect(Collectors.toMap(
name -> name, // Key: the name itself
name -> name.length() // Value: length of the name
));
// Result: {Alice=5, Bob=3, Charlie=7}
Code language: JavaScript (javascript)
Joining Strings
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
String result = names.stream()
.collect(Collectors.joining(", "));
// Result: Alice, Bob, Charlie
Code language: JavaScript (javascript)
Grouping Elements
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
Map<Integer, List<String>> namesByLength = names.stream()
.collect(Collectors.groupingBy(String::length));
// Result: {3=[Bob], 5=[Alice], 6=[David], 7=[Charlie]}
Code language: JavaScript (javascript)
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Map<Boolean, List<String>> longNames = names.stream()
.collect(Collectors.partitioningBy(name -> name.length() > 3));
// Result: {false=[Bob], true=[Alice, Charlie]}
Code language: JavaScript (javascript)
Partitioning Elements
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
LinkedList<String> linkedList = names.stream()
.collect(Collectors.toCollection(LinkedList::new));
// Result: LinkedList containing [Alice, Bob, Charlie]
Code language: JavaScript (javascript)
 Custom Collection Use toCollection() to collect into a specific collection type
Collecting elements with streams in Java provides a versatile mechanism for aggregating data into different types of collections or structures, making it a powerful tool for data manipulation and aggregation tasks in Java programming.