.flatMap(e -> Stream.of(e.split(" "))) -> Returns a stream of R instead of just R
1
2
3
4
5
6
7
8
9
List<String>list=Arrays.asList("Zello Some","New Some","Thing New","zGood");List<String>list2=list.stream().flatMap(e->Stream.of(e.split(" "))).peek(s->System.out.println(s+" ")).distinct().sorted().collect(Collectors.toList());System.out.println("Unique words = "+list2);
Output
Zello
Some
New
Some
Thing
New
zGood
Unique words = [New, Some, Thing, Zello, zGood]
Note the difference with map method
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
Both map and flatMap take in a Function <T, R>
flatMap R -> Stream<? extends R> whereas map R -> R
flatMap is useful when you want to split the incoming stream elements into another stream of same type.
6.2 Read files using lambda improvements: Files.find, lines(), walk()
Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use.
Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing
Most streams are backed by collections, arrays, or generating functions, require no special closing.
The below methods opens up some of other file resource and should be used with the try-with-resources to ensure that the stream’s close method is invoked.
walk:
find:
lines
The returned stream encapsulates a Reader so this should be called with try-with-resources.
IntStreamintStream=IntStream.range(1,20);intStream.forEach(i->System.out.print(i+" "));System.out.println("\nAverage: "+IntStream.range(1,20).average());// Note it includes numbers upto 20IntStreamintStream2=IntStream.rangeClosed(1,20);intStream2.forEach(i->System.out.print(i+" "));Output:12345678910111213141516171819Average:OptionalDouble[10.0]1234567891011121314151617181920
IntSummaryStatistics (not mentioned for exam)
A state object for collecting statistics such as count, min, max, sum, and average.