Java 8 - Stream API and its benefits with simple examples

  • Stream API ( java.util.stream ) is a new feature introduced in Java 8, which allows parallel or serial operations on Collections
  • Collection interface provides default methods stream() and parallelStream() which returns the Stream object
  • Stream object allows operations such as filter, map, reduce, find, match , sort etc
  • Parallel streaming makes use of new ForkJoinPool introduced in Java 8 which leverages available CPU cores to achieve parallelism and thereby performance

Example

package com.codeforeach.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

class StreamAPIDemo {
  public static void main(String[] args) {
    
    List<Bag> list = new ArrayList<>();

    // adding numbers ( 0 -9 ) to list 
    for (int i = 0; i < 10; i++)
      list.add(new Bag(i));

    // 1) filter the list to get even weight bags using sequential stream
    list.stream().filter(a -> a.getWeight() % 2 == 0).forEach(System.out::print);
    
    // 2) sum of even weight bags using sequential stream
    int sum = list.stream().filter(a -> a.getWeight() % 2 == 0).mapToInt(a -> a.getWeight()).sum();
    
    System.out.println("\nsum of even numbers = " + sum);

    // 3) filter list to get even weight bags using parallel stream
    list.parallelStream().filter(a -> a.getWeight() % 2 == 0).forEach(System.out::print);
    
  }
}

class Bag {
  int weight ;
  Bag(int weight) {
    this.weight = weight;
  }
  public String toString() {
    return "Bag(" + weight + "kg) ";
  }
  int getWeight() {
    return weight;
  }
}

 

Bag(0kg) Bag(2kg) Bag(4kg) Bag(6kg) Bag(8kg)
sum of even weight bags = 20
Bag(6kg) Bag(8kg) Bag(2kg) Bag(0kg) Bag(4kg)

Code explained

Add bags with weights to list
1) get sequential stream using stream(), filter to get even weight bags , print using forEach and method reference
2) get sequential stream using stream(), filter to get even weight bags , get integer stream using mapToInt(ToIntFunction<T>) and get sum using sum()
3) get parallel stream using paralleStream(), filter to get even weight bags , print using forEach and method reference

Note : filter, map, reduce , sort etc are Intermediate functions which return again a Stream and forEach, sum() etc are Terminal functions which return either value or nothing.

 

References

Java 8 – new features and enhancements with examples

Stream API docs

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

www.000webhost.com