Friday, 22 April 2016

[Java 8] Streams


[Java 8] Streams

A stream represents a sequence of elements and supports different kind of operations.
Lists and Sets support new methods stream() and parallelStream() to either create a sequential or a parallel stream. Parallel streams are capable of operating on multiple threads.

Examples
List<String> myList =
    Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
    .stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);

// C1
// C2


In the above example filter, map and sorted are intermediate operations whereas forEach is a terminal operation.

We can define collection on the go when working with streams.
Arrays.asList("a1", "a2", "a3")
    .stream()
    .findFirst()
    .ifPresent(System.out::println);

// a1

We don't have to create collections in order to work with streams.
Above statement is equivalant to :
Stream.of("a1", "a2", "a3")
    .findFirst()
    .ifPresent(System.out::println);

// a1

IntStream, LongStream and DoubleStream workes with primitive data types
IntStream.range(1, 4)
    .forEach(System.out::println);

// 1
// 2
// 3

Primitive streams support the additional terminal aggregate operations sum() and average()
Arrays.stream(new int[] {1, 2, 3})
    .map(n -> 2 * n + 1)
    .average()
    .ifPresent(System.out::println);  

// 5.0


Transform a object stream to a primitive stream, using mapToInt(), mapToLong() and mapToDouble()
Stream.of("a1", "a2", "a3")
    .map(s -> s.substring(1))
    .mapToInt(Integer::parseInt)
    .max()
    .ifPresent(System.out::println);
// 3

and vice versa using mapToObj()
IntStream.range(1, 4)
    .mapToObj(i -> "a" + i)
    .forEach(System.out::println);
// a1
// a2
// a3


MIXED EXAMPLE
Stream.of(1.0, 2.0, 3.0)
    .mapToInt(Double::intValue)
    .mapToObj(i -> "a" + i)
    .forEach(System.out::println);

// a1
// a2
// a3

No comments:

Post a Comment

Note: only a member of this blog may post a comment.