The Stream concept is introduced in Java 8 and the main objective of this concept is to process the contents of the Collection with Functional Programming(Lambda Expression).
Q. How to create Stream Objects?
We can create a Stream object from the collection by using the stream() method of the Collection interface. stream() is the default method in all the Collections in the 1.8 version.
Q. How can we process Objects of Collection by using Stream?
Once we have the stream, by using it we can process the object of that collection. we use either filter() or map() method.
1. takeWhile():
Syntax: default Stream<T> takeWhile (Predicate<? super T> predicate);
it takes elements from the Steam as long as Predicate returns true, if Predicate returns false at that point onwards it won't process the rest stream objects. there is no guarantee that it will process each object of the Stream.
example:
1 2 |
List<Integer> listOfInteger = Arrays.ofList(2,4,3,9,5,8); List<Integer> listOfTakeWhile = listOfInteger.stream().takeWhile(i->i%2==0).collect(Collectors.toList()); |
2. dropWhile():
Syntax: default Stream<T> dropWhile (Predicate<? super T> predicate);
it is opposite to takeWhile(), it drops the objects instead of taking them as long as Predicate returns true, if Predicate returns false then the rest of the Stream return.
example:
List<Integer> listOfInteger = Arrays.asList(2,4,3,9,5,8); List<Integer> listOfDropWhile = listOfInteger.stream().dropWhile(i->i%2==0).collect(Collectors.toList());
3. Stream.itearte():
i. with 2 args, it takes an initial value and a function that provides the next value.
Syntax: static <T> Stream<T> iterate (T seed, UnaryOperator<T> f);
example:
i) Stream.iterate(1, x-> x+1).forEach(System.out::println);// infinite loop ii) Stream.iterate(1, x-> x+1).limit(5).forEach(System.out::println);//limit the loop
ii. with 3 args,
Syntax: static <T> Stream<T> iterate(T seed, Predicate<T> hasNext, UnaryOperator<T> next);
The main issue with the 2 args iterate() method is there may be a situation where it can go in an infinite loop, to avoid this issue we limit the iteration with this method. This method takes an initial value, terminate Predicate and a function that provide the next value.
example:
Stream.iterate(1, x-> x < 5, x-> x + 1).forEach(System.out::println);
4. ofNullable():
Syntax: static <T> Stream<T> ofNullable (T t);
this method checks whether the given element is null or not, if it is not null, then this method returns the Stream of that element, in a null situation this method returns an empty stream. the main merit of this method is, we can avoid NullPointerException and do not need to implement the null check condition everywhere.
example:
List<String> listOfStrings = Arrays.asList("A", "B", null, "E", "G", null); List<String> listOfNonNullStrings = listOfStrings.stream().flatMap(str -> Stream.ofNullable(str)).collect(Collectors.toList());