Streams is a new concept or should be specifically mentioned as an ‘Interface’ that’s been introduced in Java 8. Please make sure to not get confused it with Java I/O Streams. The stream is a sequence of objects and the objective of Stream API is to process the collection of objects. In this post, we will see how to double the numbers present in an ArrayList with the help of Java 8 Streams.
Let's check how to double ArrayList with the power of Streams...!!! Share on XLet’s jump onto the code directly without wasting any more time and below code, I’ll explain you the key methods that have been used in the code.
Let’s say: There is an ArrayList of 10 integer values as shown below. Using Streams, we are going to double each ArrayList value.
Syntax
1 | List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import static java.util.stream.Collectors.toList; import java.util.Arrays; import java.util.List; public class DoubleNumbersOfArrayListUsingStreams { public static void main(String[] args) { List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); List<Integer> doubleArrayListNumbers = list.stream() .map(i -> i*2) .collect(toList()); System.out.println("Double values of ArrayList Integers: "+doubleArrayListNumbers); } } |
Output:
1 | Double values of ArrayList Integers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] |
Let me explain a little bit about methods that are being used here from Stream API:
1. map:
Package:
Description:
Returns a stream consisting of the results of applying the given function to the elements of this stream.
Operation Type:
intermediate operation
Type Parameters:
- <R> The element type of the new stream
Parameters:
- mapper a non-interfering, stateless function to apply to each element
Returns:
- the new stream
2. Collect:
Package:
Description:
Performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple – level grouping or partitioning.
If the stream is parallel, and the Collector is concurrent, and either the stream is unordered or the collector is unordered, then a concurrent reduction will be performed(see Collector for details on concurrent reduction.)
Operation Type:
This is a terminal operation.
Type Parameters:
<R> the type of the result
<A> the intermediate accumulation type of the Collector
Parameters:
collector the Collector
describing the reductionReturns: the result of the reduction
Returns:
- the result of the reduction
Let's check how to double ArrayList with the power of Streams...!!! Share on X
If you like this post, please check out my other similar posts:
Double the even / odd numbers of a specified ArrayList using Streams