Using Guava’s Collectors for Collecting Streams to Immutable Collections in Java
Guava is a set of core libraries from Google that includes new collection types. For example, we multimap and multisets, immutable collections, a graph library, and utilities for concurrency. It is used by many companies. In this article, we are going to see how to use Guava’s Collectors for Collecting Streams to Immutable Collections in Java. To use guava we need to add Maven dependency. Otherwise, we have to add this library externally to our project.
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>22.0</version> </dependency>
Let us go through the same important concepts involving methods been involved prior before jumping to implementation for clarity’s sake of understanding. The concept of streams plays a major role here that is been introduced in Java 8. A stream represents a sequence of elements and supports different kinds of operations to perform computations or bulk operations on those elements.
- A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
- Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
- Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
static IntStream range (int start, int end)
Return type: An integer stream
Description: This method is used to return a sequential order of Integer Stream
Stream intStream boxed()
Return type: Stream
Description: This method returns Stream consisting of the elements of this stream
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Note: In the above output we have printed an immutable list of Integers. If we try to modify the list, it will throw an UnsupportedOperationException.
Exception in thread "main" java.lang.UnsupportedOperationException at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:220) at james.App.main(App.java:15)