The Stream API provides a way to work with collections of data in a declarative manner, using functional programming constructs
It was introduced in Java 8 as a way to make it easier to process data in parallel, and it has since become an essential tool for developers working with large data sets.
Stream API gives the ability to work with collections in a lazy and parallel manner. This means that the operations are only executed when necessary, and that they can be split across multiple threads to take advantage of multi-core processors. This can lead to significant performance improvements when working with large data sets.
The Java Stream API has several key features that make it a powerful tool for working with collections of data. Here are some of the most important features of Java Streams:
1. Java Streams are lazy in processing , meaning that intermediate operations are only performed when a terminal operation is invoked. This allows for more efficient processing of large data sets, as only the necessary data is processed.
Intermediate Operations:
- filter(Predicate<T> predicate) - filters the stream based on a given predicate
- map(Function<T, R> mapper) - transforms the elements of the stream using the given function
- flatMap(Function<T, Stream<R>> mapper) - transforms each element of the stream into a stream of other elements, and flattens the resulting stream
- distinct() - returns a stream with distinct elements
- sorted() - returns a stream with elements sorted in natural order
- peek(Consumer<T> action) - applies the given action to each element of the stream, without modifying the stream itself
- limit(long maxSize) - returns a stream with a maximum size of maxSize
- skip(long n) - returns a stream with the first n elements skipped
Terminal Operations:
- forEach(Consumer<T> action) - applies the given action to each element of the stream
- collect(Collector<T, A, R> collector) - collects the elements of the stream into a collection or other data structure
- reduce(T identity, BinaryOperator<T> accumulator) - reduces the elements of the stream to a single value using the given binary operator and an initial value
- count() - returns the number of elements in the stream
- anyMatch(Predicate<T> predicate) - returns true if any element of the stream matches the given predicate, otherwise false
- allMatch(Predicate<T> predicate) - returns true if all elements of the stream match the given predicate, otherwise false
- noneMatch(Predicate<T> predicate) - returns true if no element of the stream matches the given predicate, otherwise false
- findFirst() - returns the first element of the stream, or an empty Optional if the stream is empty
- findAny() - returns any element of the stream, or an empty Optional if the stream is empty. This operation may be performed more efficiently than findFirst() in some cases
2. Streams do not change the original data , they only provides the results as per the pipelined method
3. Streams can be processed in parallel, which means that the processing can be distributed across multiple threads. This can lead to significant performance improvements, especially when working with large datasets.
4. A stream is not a data structure instead it takes input from the Collections, Arrays, or I/O channels.
5. ava Streams can be used with any collection that implements the Collection interface, as well as with arrays and other data structures. This makes it easy to integrate Java Streams into existing code.
Java Stream Example :
We need a list of objects to work with the stream API, we are going to make a list of employees for our example.
public class Employee {
private String empId;
private String firstName;
private String lastName;
private String email;
private String gender;
private String newJoiner;
private int salary;
private int rating;
//Constructor and getter setters
}
public class StreamExample {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("59-385-1088","Zacharias","Schwerin","zchwerin@gmail.com","Male","True",101146,0),
new Employee("73-274-6476","Kyle","Frudd","kfrudd1@ovh.net","Male","FALSE",29310,2),
new Employee("85-939-9584","Axe","Gumb","agumb2@twitter.com","Female","FALSE",62291,4),
new Employee("08-180-8292","Robinet","Batterham","rbatterham3@last.fm","Male","FALSE",142439,4),
new Employee("21-825-2623","Ulick","Burrel","uburrel4@google.ru","Male","FALSE",128764,5),
new Employee("66-708-5539","Tailor","Ridding","Ridding","Female","FALSE",152924,4),
new Employee("81-697-2363","Joete","Braybrooke","jbraybrooke6@prnewswire.com","Male","TRUE",128907,0),
new Employee("63-019-1110","Elroy","Baverstock","ebaverstock7@ehow.com","Male","TRUE",2510,0)
);
//Filter Method - filter employee who as gender as MALE
employees.stream()
.filter(employee -> employee.getGender().equalsIgnoreCase("Male"))
.forEach(System.out::println);
}
}
Output for filter :
Employee{empId='59-385-1088', firstName='Zacharias', lastName='Schwerin', email='zchwerin@gmail.com', gender='Male', newJoiner='True', salary=101146, rating=0}
Employee{empId='73-274-6476', firstName='Kyle', lastName='Frudd', email='kfrudd1@ovh.net', gender='Male', newJoiner='FALSE', salary=29310, rating=2}
Employee{empId='08-180-8292', firstName='Robinet', lastName='Batterham', email='rbatterham3@last.fm', gender='Male', newJoiner='FALSE', salary=142439, rating=4}
Employee{empId='21-825-2623', firstName='Ulick', lastName='Burrel', email='uburrel4@google.ru', gender='Male', newJoiner='FALSE', salary=128764, rating=5}
Employee{empId='81-697-2363', firstName='Joete', lastName='Braybrooke', email='jbraybrooke6@prnewswire.com', gender='Male', newJoiner='TRUE', salary=128907, rating=0}
Employee{empId='63-019-1110', firstName='Elroy', lastName='Baverstock', email='ebaverstock7@ehow.com', gender='Male', newJoiner='TRUE', salary=2510, rating=0}
// sort the employee list by rating Asc
employees.stream()
.sorted(Comparator.comparing(Employee::getRating))
.forEach(System.out::println);
Output for sort :
Employee{empId='59-385-1088', firstName='Zacharias', lastName='Schwerin', email='zchwerin@gmail.com', gender='Male', newJoiner='True', salary=101146, rating=0}
Employee{empId='81-697-2363', firstName='Joete', lastName='Braybrooke', email='jbraybrooke6@prnewswire.com', gender='Male', newJoiner='TRUE', salary=128907, rating=0}
Employee{empId='63-019-1110', firstName='Elroy', lastName='Baverstock', email='ebaverstock7@ehow.com', gender='Male', newJoiner='TRUE', salary=2510, rating=0}
Employee{empId='73-274-6476', firstName='Kyle', lastName='Frudd', email='kfrudd1@ovh.net', gender='Male', newJoiner='FALSE', salary=29310, rating=2}
Employee{empId='85-939-9584', firstName='Axe', lastName='Gumb', email='agumb2@twitter.com', gender='Female', newJoiner='FALSE', salary=62291, rating=4}
Employee{empId='08-180-8292', firstName='Robinet', lastName='Batterham', email='rbatterham3@last.fm', gender='Male', newJoiner='FALSE', salary=142439, rating=4}
Employee{empId='66-708-5539', firstName='Tailor', lastName='Ridding', email='Ridding', gender='Female', newJoiner='FALSE', salary=152924, rating=4}
Employee{empId='21-825-2623', firstName='Ulick', lastName='Burrel', email='uburrel4@google.ru', gender='Male', newJoiner='FALSE', salary=128764, rating=5}
//sort the employee list by both rating and salary
employees.stream()
.sorted(Comparator.comparing(Employee::getRating))
.sorted(Comparator.comparing(Employee::getSalary))
.forEach(System.out::println);
Output :
Employee{empId='63-019-1110', firstName='Elroy', lastName='Baverstock', email='ebaverstock7@ehow.com', gender='Male', newJoiner='TRUE', salary=2510, rating=0}
Employee{empId='73-274-6476', firstName='Kyle', lastName='Frudd', email='kfrudd1@ovh.net', gender='Male', newJoiner='FALSE', salary=29310, rating=2}
Employee{empId='85-939-9584', firstName='Axe', lastName='Gumb', email='agumb2@twitter.com', gender='Female', newJoiner='FALSE', salary=62291, rating=4}
Employee{empId='59-385-1088', firstName='Zacharias', lastName='Schwerin', email='zchwerin@gmail.com', gender='Male', newJoiner='True', salary=101146, rating=0}
Employee{empId='21-825-2623', firstName='Ulick', lastName='Burrel', email='uburrel4@google.ru', gender='Male', newJoiner='FALSE', salary=128764, rating=5}
Employee{empId='81-697-2363', firstName='Joete', lastName='Braybrooke', email='jbraybrooke6@prnewswire.com', gender='Male', newJoiner='TRUE', salary=128907, rating=0}
Employee{empId='08-180-8292', firstName='Robinet', lastName='Batterham', email='rbatterham3@last.fm', gender='Male', newJoiner='FALSE', salary=142439, rating=4}
Employee{empId='66-708-5539', firstName='Tailor', lastName='Ridding', email='Ridding', gender='Female', newJoiner='FALSE', salary=152924, rating=4}
//Find the first employee
employees.stream()
.findFirst().ifPresent(System.out::println);
Output for find first example :
Employee{empId='59-385-1088', firstName='Zacharias', lastName='Schwerin', email='zchwerin@gmail.com', gender='Male', newJoiner='True', salary=101146, rating=0}

Comments
Post a Comment