30 Sep
30Sep

This is a blog related to the Java 8 new features introduced as part of the functional programming approach.

Java 8 Streams
Streams are equivalent of the sequence from the functional programming language.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.


 What are the features of Streams?

Stream provides following features:

  • Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations.
  • Stream is functional in nature. Operations performed on a stream does not modify it's source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.
  • Stream is lazy and evaluates code only when required.
  • The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.


Convert List into map using streams API

// Converting Product List into a Map  

   Map productPriceMap =    productsList.stream()  

                                                  .collect(Collectors.toMap(p->p.id, p->p.name));



 Method reference by streams?
  List productPriceList =   productsList.stream()  
                   .filter(p -> p.price > 30000) // filtering data  
                   .map(Product::getPrice)         // fetching price by referring getPrice method                   .collect(Collectors.toList());  // collecting as list


 What are the ways to generate Streams in Java?
 There are two ways to generate streams in java.
  With Java 8, Collection interface has two methods to generate a Stream.
  • stream() − Returns a sequential stream considering collection as its source.
  • parallelStream() − Returns a parallel Stream considering collection as its source. 


Comaprator in Lamda ways

1. Classic Comparator example.

    Comparator<Developer> byName = new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getName().compareTo(o2.getName());
        }
    };Copy

2. Lambda expression equivalent.

    Comparator<Developer> byName =                           (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());

Comments
* The email will not be published on the website.
I BUILT MY SITE FOR FREE USING