As part of Java 8 new features, lambda expressions are now supported (Project Lambda). See this very easy-to-read article from Brian Goetz State of the Lambda but more importantly focusing more on streams: State of the Lambda: Libraries Edition
// From parameters
Stream<String> s = Stream.of("a", "b");
// From arrays
Arrays.stream(myArray)
// From collections
myCollections.stream()
// you also have specialized streams like IntStream, LongStream, DoubleStream, some example below:
IntStream ints = IntStream.range(0, 10_000);
IntStream rdInts = new Random().ints(1000);filter()mapToInt,mapToObjmap()collect()findAny(),findFirst(),noneMatch()forEach()distinct()sorted()sorted(Comparator<? super T>)
These functions can be applied to
- Optional
- Stream
map() returns a stream consisting of the results of applying the parameter function to the elements of the stream. This can potentially leads to producing output of type Stream<Stream<R>>, which are hard to work with. In such cases, flatmap() can be used (see below).
flatMap(), as it names indicates, flattens the result. Unlike map() which is only performing a transformation on each element of the stream, flatMap() also perform flattening of the inner streams in the stream resulting from the transformation.
Example:
String[] arr = { "map", "flatmap" };
Arrays.stream(arr).flatMap(word -> word.chars().mapToObj(o -> (char) o)).forEach(System.out::println);This prints:
m
a
p
f
l
a
m
a
p
Example, use: mystream.collect(Collectors.toList()), mystream.collect(Collectors.toCollection(ArrayList::new)
Example, use: mystream.toArray(String[]::new)
reduce(identity, BinaryOperator<T> accumulator)
Example:
String[] myArray = { "Where", "is", "my", "stream", "?" };
String result = Arrays.stream(myArray)
.reduce("", (a,b) -> a + " " + b);
assert result.equals(" Where is my stream ?"); Others...
sum()average()count()
The motivation behind the stream API was mostly to enable easy parallelization
Use these methods:
myStream.parallel()myCollection.parallelStream()