Tutorial by Examples

A Stream is a sequence of elements upon which sequential and parallel aggregate operations can be performed. Any given Stream can potentially have an unlimited amount of data flowing through it. As a result, data received from a Stream is processed individually as it arrives, as opposed to performin...
Collect with toList() and toSet() Elements from a Stream can be easily collected into a container by using the Stream.collect operation: System.out.println(Arrays .asList("apple", "banana", "pear", "kiwi", "orange") .stream() .filter...
It is possible to generate a Stream that does not end. Calling a terminal method on an infinite Stream causes the Stream to enter an infinite loop. The limit method of a Stream can be used to limit the number of terms of the Stream that Java processes. This example generates a Stream of all natural...
A Stream will only be traversed when there is a terminal operation, like count(), collect() or forEach(). Otherwise, no operation on the Stream will be performed. In the following example, no terminal operation is added to the Stream, so the filter() operation will not be invoked and no output will...
The groupingBy(classifier, downstream) collector allows the collection of Stream elements into a Map by classifying each element in a group and performing a downstream operation on the elements classified in the same group. A classic example of this principle is to use a Map to count the occurrence...
Note: Before deciding which Stream to use please have a look at ParallelStream vs Sequential Stream behavior. When you want to perform Stream operations concurrently, you could use either of these ways. List<String> data = Arrays.asList("One", "Two", "Three", &q...
You may need to convert a Stream emitting Optional to a Stream of values, emitting only values from existing Optional. (ie: without null value and not dealing with Optional.empty()). Optional<String> op1 = Optional.empty(); Optional<String> op2 = Optional.of("Hello World");...
All java Collection<E>s have stream() and parallelStream() methods from which a Stream<E> can be constructed: Collection<String> stringList = new ArrayList<>(); Stream<String> stringStream = stringList.parallelStream(); A Stream<E> can be created from an arra...
Java 8 provides classes called IntSummaryStatistics, DoubleSummaryStatistics and LongSummaryStatistics which give a state object for collecting statistics such as count, min, max, sum, and average. Java SE 8 List<Integer> naturalNumbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); IntSu...
Example: Get a Stream of 30 elements, containing 21st to 50th (inclusive) element of a collection. final long n = 20L; // the number of elements to skip final long maxSize = 30L; // the number of elements the stream should be limited to final Stream<T> slice = collection.stream().skip(n).li...
Variable declaration for examples: Collection<String> abc = Arrays.asList("a", "b", "c"); Collection<String> digits = Arrays.asList("1", "2", "3"); Collection<String> greekAbc = Arrays.asList("alpha", "be...
Java does not have a Char Stream, so when working with Strings and constructing a Stream of Characters, an option is to get a IntStream of code points using String.codePoints() method. So IntStream can be obtained as below: public IntStream stringToIntStream(String in) { return in.codePoints(); ...
List<String> data = new ArrayList<>(); data.add("Sydney"); data.add("London"); data.add("New York"); data.add("Amsterdam"); data.add("Mumbai"); data.add("California"); System.out.println(data); List<String> sor...
Java provides specialized Streams for three types of primitives IntStream (for ints), LongStream (for longs) and DoubleStream (for doubles). Besides being optimized implementations for their respective primitives, they also provide several specific terminal methods, typically for mathematical operat...
Analog to get a collection for a Stream by collect() an array can be obtained by the Stream.toArray() method: List<String> fruits = Arrays.asList("apple", "banana", "pear", "kiwi", "orange"); String[] filteredFruits = fruits.stream() ....
It is possible to find the first element of a Stream that matches a condition. For this example, we will find the first Integer whose square is over 50000. IntStream.iterate(1, i -> i + 1) // Generate an infinite stream 1,2,3,4... .filter(i -> (i*i) > 50000) // Filter to find element...
Streams of elements usually do not allow access to the index value of the current item. To iterate over an array or ArrayList while having access to indexes, use IntStream.range(start, endExclusive). String[] names = { "Jon", "Darin", "Bauke", "Hans", "M...
A Stream of items that are in turn streamable can be flattened into a single continuous Stream: Array of List of Items can be converted into a single List. List<String> list1 = Arrays.asList("one", "two"); List<String> list2 = Arrays.asList("three&quot...
Simple case without duplicate keys Stream<String> characters = Stream.of("A", "B", "C"); Map<Integer, String> map = characters .collect(Collectors.toMap(element -> element.hashCode(), element -> element)); // map = {65=A, 66=B, 67=C} ...
It is sometimes useful to create random Strings, maybe as Session-ID for a web-service or an initial password after registration for an application. This can be easily achieved using Streams. First we need to initialize a random number generator. To enhance security for the generated Strings, it i...

Page 1 of 2