java streams tutorial
Overview
In this in-depth tutorial, we’ll go through the practical usage of Java 8 Streams from creation to parallel execution.
To understand this material, readers need to have a basic knowledge of Java 8 (lambda expressions, Optional, method references) and of the Stream API. If you aren’t familiar with these topics, please take a look at our previous articles – New Features in Java 8 and Introduction to Java 8 Streams.
Further reading:
Lambda Expressions and Functional Interfaces: Tips and Best Practices
Tips and best practices on using Java 8 lambdas and functional interfaces.
Read more →
Guide to Java 8’s Collectors
The article discusses Java 8 Collectors, showing examples of built-in collectors, as well as showing how to build custom collector.
Read more →
2. Stream Creation
There are many ways to create a stream instance of different sources. Once created, the instance will not modify its source, therefore allowing the creation of multiple instances from a single source.
2.1. Empty Stream
The empty() method should be used in case of a creation of an empty stream:
1
Stream<String> streamEmpty = Stream.empty();
Its often the case that the empty() method is used upon creation to avoid returning null for streams with no element:
1
2
3
public Stream<String> streamOf(List<String> list) {
return list == null || list.isEmpty() ? Stream.empty() : list.stream();
}
2.2. Stream of Collection
Stream can also be created of any type of Collection (Collection, List, Set):
1
2
Collection<String> collection = Arrays.asList(“a”, “b”, “c”);
Stream<String> streamOfCollection = collection.stream();
2.3. Stream of Array
Array can also be a source of a Stream:
1
Stream<String> streamOfArray = Stream.of(“a”, “b”, “c”);
They can also be created out of an existing array or of a part of an array:
1
2
3
String[] arr = new String[]{“a”, “b”, “c”};
Stream<String> streamOfArrayFull = Arrays.stream(arr);
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
2.4. Stream.builder()
When builder is used the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream<Object>:
1
2
Stream<String> streamBuilder =
Stream.<String>builder().add(“a”).add(“b”).add(“c”).build();
2.5. Stream.generate()
The generate() method accepts a Supplier<T> for element generation. As the resulting stream is infinite, developer should specify the desired size or the generate() method will work until it reaches the memory limit:
Dell Boomi Online Training
java streams tutorial
For More: Online Training
India|US|UK|Canada|Australia|Germany|Philippines|New Zealand|Switzerland
Mumbai|Kolkata|Bangalore|Chennai|Kerala|Pune|Hyderabad|Lucknow|New Delhi