Java8features Streamapi
Java8features Streamapi
Java
Stream API
@techwithvishalraj
Stream API
Java provides a new additional package in Java 8 called
java.util.stream.
This package consists of classes, interfaces and enum to allows
functional-style operations on the elements.
A stream is a sequence of elements that supports various
operations to perform computations upon those elements. Streams
do not store elements; they are functional-style constructs that
allow for processing elements on-demand.
The elements of a stream are only visited once during the life of a
stream.
filter()
syntax: Stream<T> filter(Predicate<? super T> predicate)
map()
syntax: <R> Stream<R> map(Function<? super T, ? extends R> mapper)
sorted()
List<Integer> sortedlist = list.stream().sorted().toList();
Sop(sortedlist); ----> [0, 1, 2, 3, 3, 4, 5, 6, 8]
@techwithvishalraj
distinct()
It eliminates duplicate elements, ensuring that each element in the
resulting stream is unique.
skip(long n)
skips the first n elements of the stream and returns a new stream
consisting of the remaining elements. If the stream contains fewer than
n elements then empty stream is returned.
limit(lomg maxSize)
returns a stream consisting of the first maxSize elements of the original
stream. If the original stream contains fewer than maxSize elements,
then all elements of the original stream is returned.
class Person{
String name;
List<Long> phoneNo;
anyMatch()
Syntax: boolean anyMatch(Predicate<? super T> predicate)
It check whether any element of the stream matches a given predicate.
T result = identity;
for (T element : this stream)
result = accumulator.apply(result, element)
return result;
class Employee{
private String name;
private Integer age;
private String city;
class Employee{
private String name;
private Integer age;
private String city;
private Integer salary;
// constructor, getters and setters
}
public class Test {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("baburao", 45, "mumbai", 4500),
new Employee("ram", 27, "kalkatta", 0),
new Employee("shyam", 25, "jaipur", 1000),
new Employee("sam", 25, "delhi", 1000));
employees.stream().sorted(Comparator
.comparing(Employee::getSalary)
.thenComparing(Employee::getAge)
.thenComparing(Employee::getCity))
.forEach(x-> System.out.println(x.getName()+
" : "+ x.getAge()+" : "+ x.getCity()+
" : "+x.getSalary()));
}
} output: ram : 27 : kalkatta : 0
sam : 25 : delhi : 1000
shyam : 25 : jaipur : 1000
baburao : 45 : mumbai : 4500
HashMap Sorting @techwithvishalraj
Thank
you!
vishal-bramhankar
techwithvishalraj
Vishall0317