Java Streams are a powerful abstraction for processing sequences of elements, like collections, arrays, or I/O resources. They provide a modern and concise approach to handling data transformations, filters, and operations on large datasets. However, after performing the desired operations on a stream, you may sometimes need to convert it back to a collection (such as List, Set, or Map) for further processing.
This guide will walk you through various ways to convert a stream back to a collection using Java’s Stream API, providing real-world examples and clear explanations. Whether you’re using a List, Set, or even a Map, we’ll cover it all.
1. Converting a Stream to a List
One of the most common use cases when converting a stream is to obtain a List. Lists are ordered collections that allow duplicate elements and can be accessed via an index. The method collect(Collectors.toList())
is typically used to collect the elements of a stream into a list.
public class StreamToListExample {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 4, 5);
List squaredNumbers = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println(squaredNumbers);
}
}
In this example, we first create a list of integers and then use a stream to square each element. Finally, we collect the squared numbers back into a List.
2. Converting a Stream to a Set
A Set is a collection that doesn’t allow duplicate elements. If you need to convert a stream to a Set, you can use Collectors.toSet()
. This is particularly useful when you want to remove duplicates from the original stream.
public class StreamToSetExample {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 2, 3, 4, 5, 5);
Set uniqueNumbers = numbers.stream()
.collect(Collectors.toSet());
System.out.println(uniqueNumbers);
}
}
Here, we have a list of numbers with duplicates. By converting the stream to a Set, all duplicate values are eliminated.
3. Converting a Stream to a Map
Sometimes, it is necessary to convert a stream into a Map, where each element of the stream is mapped to a key-value pair. The Collectors.toMap()
method is used for this conversion.
public class StreamToMapExample {
public static void main(String[] args) {
List words = Arrays.asList("apple", "banana", "cherry");
Map wordLengthMap = words.stream()
.collect(Collectors.toMap(String::length, word -> word));
System.out.println(wordLengthMap);
}
}
In this example, we take a list of words and create a map where the key is the length of each word, and the value is the word itself. The toMap()
collector provides a very flexible way to convert a stream into a Map.
4. Other Ways to Collect the Stream
Besides lists, sets, and maps, Java provides several other collection types that can be used to collect stream elements, such as:
- Queue: To collect elements into a
Queue
, you can useCollectors.toCollection(LinkedList::new)
. - Custom Collection: If you have a custom collection, you can collect it using
Collectors.toCollection()
with a supplier of the desired collection type.
public class StreamToQueueExample {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 4, 5);
Queue numberQueue = numbers.stream()
.collect(Collectors.toCollection(LinkedList::new));
System.out.println(numberQueue);
}
}
5. Conclusion
Converting a Java stream back into a collection is a crucial task when you need to perform further operations on the resulting data. Java’s Stream API provides a variety of collectors that can convert streams into different collection types like List, Set, and Map, as well as other custom collections.
Note: Streams are a one-time use construct. Once a stream is consumed (for example, by calling a terminal operation like collect()
), it cannot be reused. Be sure to reinitialize the stream if you need to process the data again.