Skip to main content

Java Stream API




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

Popular posts from this blog

How to create Annotation in Spring boot

 To create Custom Annotation in JAVA, @interface keyword is used. The annotation contains :  1. Retention :  @Retention ( RetentionPolicy . RUNTIME ) It specifies that annotation should be available at runtime. 2. Target :  @Target ({ ElementType . METHOD }) It specifies that the annotation can only be applied to method. The target cane be modified to:   @Target ({ ElementType . TYPE }) for class level annotation @Target ({ ElementType . FIELD }) for field level annotation @Retention ( RetentionPolicy . RUNTIME ) @Target ({ ElementType . FIELD }) public @ interface CustomAnnotation { String value () default "default value" ; } value attribute is defined with @ CustomAnnotation annotation. If you want to use the attribute in annotation. A single attribute value. Example : public class Books {           @CustomAnnotation(value = "myBook")     public void updateBookDetail() {         ...

Kafka And Zookeeper SetUp

 Kafka And Zookeeper SetUp zookeeper download Link : https://www.apache.org/dyn/closer.lua/zookeeper/zookeeper-3.8.3/apache-zookeeper-3.8.3-bin.tar.gz Configuration: zoo.conf # The number of milliseconds of each tick tickTime =2000 # The number of ticks that the initial # synchronization phase can take initLimit =10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit =5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir =/tmp/zookeeper # the port at which the clients will connect clientPort =2181 4 char whitelist in command arguments 4lw.commands.whitelist =* Start ZooKeeper Server $ bin/zkServer.sh start Check zookeeper status dheeraj.kumar@Dheeraj-Kumar bin % echo stat | nc localhost 2181 stat is 4 character whitelisted argument  Check Kafka running status : echo dump | nc localhost 2181 | grep broker Responsibility of Leader in Zookeeper: 1. Distrib...

Cache Policy

Cache policies determine how data is stored and retrieved from a cache, which is a small and fast storage area that holds frequently accessed data to reduce the latency of accessing that data from a slower, larger, and more distant storage location, such as main memory or disk. Different cache policies are designed to optimize various aspects of cache performance, including hit rate, latency, and consistency. Here are some common types of cache policies: Least Recently Used (LRU): LRU is a commonly used cache replacement policy. It evicts the least recently accessed item when the cache is full. LRU keeps track of the order in which items were accessed and removes the item that has not been accessed for the longest time. First-In-First-Out (FIFO): FIFO is a simple cache replacement policy. It removes the oldest item from the cache when new data needs to be stored, regardless of how frequently the items have been accessed. Most Recently Used (MRU): MRU removes the most recently accessed ...