Why we need streams in java?
1) A stream does not store data. An operation on a stream does not modify its source, but simply produces a result. Without stream we need to have iterator or foreach to get item in collection.
2) You can add to or remove elements from collections. But, you can’t add to or remove elements from streams. Stream consumes a source, performs operations on it and returns a result.
3) Streams can be traversed only once. If you traverse the stream once, it is said to be consumed. To traverse it again, you have to get new stream from the source again. But, collections can be traversed multiple times.
List<Integer> numbers = Arrays.asList(4, 2, 8, 9, 5, 6, 7);
Stream<Integer> numbersGreaterThan5 = numbers.stream().filter(i -> i > 5);
//Traversing numbersGreaterThan5 stream first time
numbersGreaterThan5.forEach(System.out::println);
//Second time traversal will throw error
//Error : stream has already been operated upon or closed
numbersGreaterThan5.forEach(System.out::println);
4) Collections elements are computed at the beginning itself. But, streams are lazily constructed i.e intermediate operations are not evaluated until terminal operation is invoked.
//Here, not all numbers are evaluated.
//numbers are evaluated until 3 numbers >= 5 are found.
Arrays.asList(4, 2, 8, 9, 5, 6, 7).stream().filter(i -> i >= 5).limit(3).forEach(System.out::println);
Operations done by streams are classified as - filtering, matching and mapping
No comments:
Post a Comment