2018-10-21

Java - Stream Operations and Pipelines

java.util.stream 

This package allows you to have a declarative presentation
of the procedures that can be subsequently applied to the data, also in parallel; these
procedures are presented as streams, which are objects of the Stream interface. For
better transition from the traditional collections to streams, two default methods
(stream() and parallelStream()) were added to the java.util.Collection interface along
with the addition of new factory methods of stream generation to the Stream interface.

This approach takes advantage of the power of composition, discussed in one of the
previous chapters. Together with other design principles--encapsulation, interface,
and polymorphism--it facilitates a highly extensible and flexible design, while
lambda expressions allow you to implement it in a concise and succinct manner.
Today, when the machine learning requirements of massive data processing and the
fine-tuning of operations have become ubiquitous, these new features reinforce
the position of Java among the few modern programming languages of choice.



Using the new factory methods to create collection objects

Java 9 ways of creating collections
List.of()
Set.of()
Map.of()
Map.ofEntries()

Java 9 introduced twelve of() static factory methods for each of the three interfaces.

static List<E> of()      //Returns list with zero elements
static List<E> of(E e1)  //Returns list with one element
static List<E> of(E e1, E e2)
static List<E> of(E e1, E e2, E e3)
static List<E> of(E e1, E e2, E e3, E e4)
static List<E> of(E e1, E e2, E e3, E e4, E e5)
static List<E> of(E e1, E e2, E e3, E e4, E e5, E e6)
static List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)
static List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
static <E> List<E> of(E... elements)

these methods avoid array allocation, initialization, and garbage collection overhead that is incurred by varargs calls.

Examples:

List.of("This ", "is ", "created ", "by ", "List.of()").forEach(System.out::print);

Set.of("This ", "is ", "created ", "by ", "Set.of() ").forEach(System.out::print);

Map.of(1, "This ", 2, "is ", 3, "built ", 4, "by ", 5,"Map.of() ").entrySet().forEach(System.out::print);


Creating and operating on streams

List.of("This", "is", "created", "by", "List.of().stream()").stream().forEach(System.out::print);

Set.of("This", "is", "created", "by", "Set.of().stream()").stream().forEach(System.out::print);

Map.of(1, "This ", 2, "is ", 3, "built ", 4, "by ", 5,"Map.of().entrySet().stream()").entrySet().stream().forEach(System.out::print);


No comments:

Post a Comment