You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Stream API is used to process collections of objects. A stream in Java is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
There uses of Stream in Java are mentioned below:
1.Stream API is a way to express and process collections of objects.
2.Enable us to perform operations like filtering, mapping,reducing and sorting.
Here are two types of Operations in Streams:
1.Intermediate Operations
2.Terminate Operations
There are a few Intermediate Operations mentioned below:
1. map() : The map method is used to return a stream consisting of the results of applying the given function to the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x->x*x).collect(Collectors.toList());
2. filter() : The filter method is used to select elements as per the Predicate passed as an argument.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
3. sorted() : The sorted method is used to sort the stream.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().sorted().collect(Collectors.toList());
4. distinct() : It returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements.
List number = Arrays.asList(2,3,4,5);
List unique = number.list.stream().distinct().forEach(System.out::println);
5. Stream anyMatch() : It returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result.
6. Stream allMatch() : It returns whether all elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result.
Terminal Operations : Terminal Operations are the type of Operations that return the result. These Operations are not processed further just return a final result value.
There are a few Terminal Operations mentioned below:
1. collect() : The collect method is used to return the result of the intermediate operations performed on the stream.