- Streams provide extended functionality to collections.
- All collection operations except operations on Map can be extended using streams.
- Streams can either be sequential or parallel.
- Operations on sequential streams are performed on a single thread.
- Operations on parallel streams are performed concurrently on multiple threads, and so are faster than sequential streams (although item order is affected). NOTE that parallel streams are CPU intensive and should be used with care as it can lead to starvation of other processes in your application.
- Operations on streams are grouped into intermediate (transformations) and terminal (actions).
- Stream processing is triggered only by terminal operations, while intermediate operations return a new stream.
an empty stream
Stream emptyStream = Stream.empty();
creating a stream from array
Stream<Integer> streamFromArray = Stream.of(new Integer[]{1,2,3});
Stream<Integer> streamFromArray2 = Arrays.stream(new Integer[]{1,2,3});
creating a stream from a collection
IntStream oneToThree = IntStream.of(1, 2, 3);
DoubleStream oneToThree_double = DoubleStream.of(1.0, 2, 3);
LongStream oneToThree_long = LongStream.of(1L, 2, 3);
converting an Integer stream to a normal stream
Stream oneToThreeStream = IntStream.of(1, 2, 3).boxed();
creating an Integer stream from a half open range (stream of 1, 2)
IntStream oneToTwo = IntStream.range(1, 3);
creating an Integer stream from a closed range (stream of 1, 2, 3)
IntStream oneToThree_ = IntStream.rangeClosed(1, 3);
creating an Integer stream with steps using lambda (stream of 0, 2, 4)
IntStream oneToFour = IntStream.iterate(0, i -> i + 2).limit(3);
creating an Integer stream using a supplier (random Integer stream)
IntStream randomStream = IntStream.generate(() -> ThreadLocalRandom.current().nextInt(10)).limit(3);
Comments
Post a comment