Showing posts with label Stream. Show all posts

How to sum values from List, Set and Map using stream in Java 8?



Following examples shows how you can use java 8 Stream api to do summation of Integer, Double and Long in List, Set and Map.

Source code (Item.java)
public class Item {

    private Long id;
    private String name;
    private Double price;
    
    public Item(String name, Double price) {
        this.name = name;
        this.price = price;
    }
    
    /* getter - setter */

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

List
  • Summation of Integers in List.
  • Summation of Price from List of beans(Item).

Source code (ListStreamSum.java)
import com.javaquery.bean.Item;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Summation of element in List using Stream api in java 8.
 *
 * @author javaQuery
 * @date 17th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ListStreamSum {

    public static void main(String[] args) {
        /* Summation of Integers in List */
        List<Integer> integers = new ArrayList<>(Arrays.asList(10, 20, 30));

        Integer integerSum = integers.stream().mapToInt(Integer::intValue).sum();
        System.out.println("summation: " + integerSum);

        /* Summation when you have list of beans */
        Item motoG = new Item("MotoG", 100.12);
        Item iPhone = new Item("iPhone", 200.12);

        List<Item> listBeans = new ArrayList<>(Arrays.asList(motoG, iPhone));

        Double doubleSum = listBeans.stream().mapToDouble(Item::getPrice).sum();
        System.out.println("summation: " + doubleSum);
    }
}

Output
summation: 60
summation: 300.24

Set
  • Summation of Integers in Set.
  • Summation of Price from Set of beans(Item).

Source code (SetStreamSum.java)
import com.javaquery.bean.Item;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Summation of element in Set using Stream api in java 8.
 *
 * @author javaQuery
 * @date 17th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class SetStreamSum {

    public static void main(String[] args) {
        /* Summation of Integers in Set */
        Set<Integer> integers = new HashSet<>(Arrays.asList(10, 20, 30));

        Integer integerSum = integers.stream().mapToInt(Integer::intValue).sum();
        System.out.println("summation: " + integerSum);

        /* Summation when you have set of beans */
        Item motoG = new Item("MotoG", 100.12);
        Item iPhone = new Item("iPhone", 200.12);

        Set<Item> listBeans = new HashSet<>(Arrays.asList(motoG, iPhone));

        Double doubleSum = listBeans.stream().mapToDouble(Item::getPrice).sum();
        System.out.println("summation: " + doubleSum);
    }
}

Output
summation: 60
summation: 300.24

Map
  • Summation of Integers in Map as a value.
  • Summation of Integers in List as a value.
  • Summation of Price from List of beans(Item) in Map.

Source code (MapStreamSum.java)
import com.javaquery.bean.Item;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Summation of element in Map using Stream api in java 8.
 *
 * @author javaQuery
 * @date 17th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class MapStreamSum {

    public static void main(String[] args) {
        /* Summation of Integers in Map */
        Map<String, Integer> integers = new HashMap<>();
        integers.put("A", 10);
        integers.put("B", 20);
        integers.put("C", 30);

        Integer integerSum = integers.values().stream().mapToInt(Integer::intValue).sum();
        System.out.println("summation: " + integerSum);

        /* Summation when you have List/Set in Map */
        Map<String, List<Integer>> listInMap = new HashMap<>();
        listInMap.put("even_numbers", new ArrayList<>(Arrays.asList(2, 4, 6)));

        integerSum = listInMap.values().stream()
                .flatMapToInt(list -> list.stream().mapToInt(Integer::intValue))
                .sum();
        System.out.println("summation: " + integerSum);

        /* Summation when you have List/Set of beans in Map */
        Item motoG = new Item("MotoG", 100.12);
        Item iPhone = new Item("iPhone", 200.12);

        List<Item> items = new ArrayList<>(Arrays.asList(motoG, iPhone));

        Map<String, List<Item>> itemMap = new HashMap<>();
        itemMap.put("items", items);

        Double doubleSum = itemMap.values().stream()
                .flatMapToDouble(list -> list.stream().mapToDouble(Item::getPrice))
                .sum();
        System.out.println("summation: " + doubleSum);
    }
}

Output
summation: 60
summation: 12
summation: 300.24

Examples of Java 8

Java 8
Using IntStream over for loop in Java 8

How to iterate over stream and increment index value in Lambda Expression?
Many of you having trouble for increment index value inside Lambda expression because of Local variable index defined in an enclosing scope must be final or effectively final. There is an alternative for that...

How to get(collect) List of Properties (String, Double, Integer) from List of beans in Java 8?
This little excerpt shows How you can fetch List<String>, List<Double>, List<Integer>, List<Object>, etc... from List<Beans>. And it also explains the use of map method in stream.

How to convert List to Map in Java 8 using Stream API?
Code snippet demonstrate converting List<T> to Map<K,V>.

Example of Collectors minBy in Lambda expression
This static method from package java.util.stream and class Collectors used to find maximum value from given Collection. This method takes Comparator as an argument.

Example of Collectors maxBy in Lambda expression
This static method from package java.util.stream and class Collectors used to find maximum value from given Collection. This method takes Comparator as an argument.

Example of distinct in Java 8
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

How flatMap works in Java 8 with Example
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)



Example of mapToInt in Java 8
Returns an IntStream consisting of the results of applying the given function to the elements of this stream.

Example of mapToLong in Java 8
Returns a LongStream consisting of the results of applying the given function to the elements of this stream.

Example of mapToDouble in Java 8
Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.

How to sum values from List, Set and Map using stream in Java 8?

Example of distinct in Java 8

Stream<T> distinct()
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first in the encounter order is preserved.) For unordered streams, no stability guarantees are made.

Source code (Employee.java)
public class Employee {
    private String Email;
    
    public String getEmail() {
        return Email;
    }

    public void setEmail(String Email) {
        this.Email = Email;
    }

    /**
     * You've to Override `equals` and `hashCode` methods in order to work `distinct` method of `stream`.
     */
    @Override
    public boolean equals(Object obj) {
        Employee compareEmployee = (Employee) obj;
        if(this.Email != null && compareEmployee != null){
            return this.Email.equalsIgnoreCase(compareEmployee.getEmail());
        }else{
            return false;
        }
    }

    @Override
    public int hashCode() {
        if(this.Email != null && !this.Email.trim().isEmpty()){
            return this.Email.hashCode();
        }else{
            return -1;
        }
    }    
}

Source code
import java.util.ArrayList;
import java.util.List;

public class DistinctExample {
    public static void main(String[] args) {
        /* Create `List` of `String` and add duplicate records */
        List<String> listStrings = new ArrayList<>(0);
        listStrings.add("Chirag");
        listStrings.add("Vicky");
        listStrings.add("Vicky");
        
        System.out.println("Distinct Strings in `listStrings`: ");
        listStrings.stream()
                   .distinct()
                   .forEach(strName -> {
                       System.out.println("> " + strName);
                   });
        
        /* Create `List` of `Long` and add duplicate records */
        List<Long> listNumbers = new ArrayList<>(0);
        listNumbers.add(22L);
        listNumbers.add(22L);
        listNumbers.add(11L);
        
        System.out.println("Distinct Numbers in `listNumbers`: ");
        listNumbers.stream()
                   .distinct()
                   .forEach(number -> {
                       System.out.println("> " + number);
                   });
        
        /**
         * Create `List` of `Employee` and add duplicate records
         * Note: In case of Bean or Pojo you've to Override `equals` and `hashCode` methods in Bean or Pojo
         */
        List<Employee> listEmployee = new ArrayList<>(0);
        Employee employeeChirag = new Employee();
        employeeChirag.setEmail("chirag.thakor@javaquery.com");
        listEmployee.add(employeeChirag);
        
        Employee employeeVicky = new Employee();
        employeeVicky.setEmail("vicky.thakor@javaquery.com");
        listEmployee.add(employeeVicky);
        
        Employee employeeDuplicate = new Employee();
        employeeDuplicate.setEmail("vicky.thakor@javaquery.com");
        listEmployee.add(employeeDuplicate); 
        
        System.out.println("Distinct Employee in `listEmployee`: ");
        listEmployee.stream()
                    .distinct()
                    .forEach(employee -> {
                       System.out.println("> " + employee.getEmail());
                    });
    }
}

Output
Distinct Strings in `listStrings`: 
> Chirag
> Vicky
Distinct Numbers in `listNumbers`: 
> 22
> 11
Distinct Employee in `listEmployee`: 
> chirag.thakor@javaquery.com
> vicky.thakor@javaquery.com

Example of mapToLong in Java 8


LongStream mapToLong(ToLongFunction<? super T> mapper)
Returns a LongStream consisting of the results of applying the given function to the elements of this stream.

Source code (Company.java)
public class Company {
    private Long id;
    private String CompanyName;
 
 public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCompanyName() {
        return CompanyName;
    }

    public void setCompanyName(String CompanyName) {
        this.CompanyName = CompanyName;
    }
}

Source code
import java.util.ArrayList;
import java.util.List;

public class MapToLongExample {
    public static void main(String[] args) {
        /* Create an object of `Company` and set values */
        Company companyApple = new Company();
        companyApple.setId(1L);
        companyApple.setCompanyName("Apple");
        
        Company companySamsung = new Company();
        companySamsung.setId(2L);
        companySamsung.setCompanyName("Samsung");
       
        /**
         * - Create `List` of `Company`
         * - Add `companyApple` and `companySamsung` to List.
         */
        List<Company> mobileCompanies=  new ArrayList<>();
        mobileCompanies.add(companyApple);
        mobileCompanies.add(companySamsung);
        
        /**
         * JavaDoc: `mapToLong` method
         * Returns a LongStream consisting of the results of applying the given function to the elements of this stream.
         * 
         * Explanation: `.mapToLong(Company::getId)` / `.mapToLong(company -> company.getId())`
         * In this operation we are calling method `getId()` on each object of `Company` in List.
         * That returns the `LongStream` of value(Id) of all object in List.
         * At last print company `Ids`.
         */
        mobileCompanies.stream()
                       .mapToLong(Company::getId)
                       .forEach(companyID ->{
                           System.out.println(companyID);
                       });
    }
}

Explanation: .mapToLong(Company::getId) / .mapToLong(company -> company.getId())
In this operation we are calling method getId() on each object of Company in List. That returns the LongStream of value(Id) of all object in List. At last print company Ids.


Output
1
2
Other References:
Example of mapToDouble in Java 8
Example of mapToInt in Java 8

Example of mapToInt in Java 8


IntStream mapToInt(ToIntFunction<? super T> mapper);
Returns an IntStream consisting of the results of applying the given function to the elements of this stream.

Source code (Item.java)
public class Item {
    private String Name;
    private int Quantity;

    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public int getQuantity() {
        return Quantity;
    }

    public void setQuantity(int Quantity) {
        this.Quantity = Quantity;
    }
}

Source code
import java.util.ArrayList;
import java.util.List;

public class MapToIntExample {
    public static void main(String[] args) {
        /* Create an object of `Item` and set values */
        Item itemSamsungGalaxy6 = new Item();
        itemSamsungGalaxy6.setName("Samsung Galaxy 6");
        itemSamsungGalaxy6.setQuantity(20);
        
        Item itemNexus = new Item();
        itemNexus.setName("Nexus 5");
        itemNexus.setQuantity(12);
        
        /**
         * - Create `List` of `Item`
         * - Add `itemSamsungGalaxy6` and `itemNexus` to List.
         */
        List<Item> listItems = new ArrayList<>();
        listItems.add(itemSamsungGalaxy6);
        listItems.add(itemNexus);
        
        /**
         * JavaDoc: `mapToInt` method
         * Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
         * 
         * Explanation: `.mapToInt(Item::getQuantity)` / `.mapToInt(item -> item.getQuantity())`
         * In this operation we are calling method `getQuantity()` on each object of `Item` in List.
         * That returns the `IntStream` of value(Quantity) of all object in List.
         * And we are doing summation of all quantity
         */
        int totalQuantity = listItems.stream()
                                     .mapToInt(Item::getQuantity)
                                     .sum();
        
        /* Print the total quantity */
        System.out.println("Total Quantity: " + totalQuantity);
    }
}

Explanation: .mapToInt(Item::getQuantity) / .mapToInt(item -> item.getQuantity())
In this operation we are calling method getQuantity() on each object of Item in List. That returns the IntStream of value(Quantity) of all object in List. And we are doing summation of all quantity


Output
Total Quantity: 32
Other References:
Example of mapToDouble in Java 8

Example of mapToDouble in Java 8


DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.

Source code (Employee.java)
public class Employee {
    private Long id;
    private String Firstname;
    private String Lastname;
    private Double Salary;

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }

    public Double getSalary() {
        return Salary;
    }

    public void setSalary(Double Salary) {
        this.Salary = Salary;
    }
}

Source code
import java.util.ArrayList;
import java.util.List;

public class MapToDoubleExample {
    public static void main(String[] args) {
        /* Create an object of `Employee` and set values */
        Employee employeeChirag = new Employee();
        employeeChirag.setFirstname("Chirag");
        employeeChirag.setLastname("Thakor");
        employeeChirag.setSalary(93142.40D);
        
        Employee employeeVicky = new Employee();
        employeeVicky.setFirstname("Vicky");
        employeeVicky.setLastname("Thakor");
        employeeVicky.setSalary(53584.50D);        
        
        /**
         * - Create `List` of `Employee`
         * - Add `employeeChirag` and `employeeVicky` to List.
         */
        List<Employee> listItems = new ArrayList<>();
        listItems.add(employeeChirag);
        listItems.add(employeeVicky);
        
        /**
         * JavaDoc: `mapToDouble` method
         * Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
         * 
         * Explanation: `.mapToDouble(Employee::getSalary)` / `.mapToDouble(employee -> employee.getSalary())`
         * In this operation we are calling method `getSalary()` on each object of `Employee` in List.
         * That returns the `DoubleStream` of value(Salary) of all object in List.
         * And we are doing summation of all salary
         */
        Double totalSalaryPaid = listItems.stream()
                                          .mapToDouble(Employee::getSalary)
                                          .sum();
        
        /* Print the total salary paid */
        System.out.println("Total Salary Paid: " + totalSalaryPaid);
    }
}

Explanation: `.mapToDouble(Employee::getSalary)` / `.mapToDouble(employee -> employee.getSalary())
In this operation we are calling method getSalary() on each object of Employee in List. That returns the DoubleStream of value(Salary) of all object in List. And we are doing summation of all salary


Output
Total Salary Paid: 146726.9
Other References:
Example of mapToInt in Java 8
Example of mapToLong in Java 8


How flatMap works in Java 8 with Example

Stream + Java 8 + flatMap + Collection

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)

Source code (Company.java)
public class Company {
    private Long id;
    private String CompanyName;
 
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCompanyName() {
        return CompanyName;
    }

    public void setCompanyName(String CompanyName) {
        this.CompanyName = CompanyName;
    }
}

Source code (Company.java)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FlatMapExample {
    public static void main(String[] args) {
        /* Create an object of `Company` and set values */
        Company companyApple = new Company();
        companyApple.setId(1L);
        companyApple.setCompanyName("Apple");
        
        Company companySamsung = new Company();
        companySamsung.setId(2L);
        companySamsung.setCompanyName("Samsung");
       
        /**
         * - Create `List` of `Company`
         * - Add `companyApple` and `companySamsung` to List.
         */
        List<Company> mobileCompanies=  new ArrayList<>();
        mobileCompanies.add(companyApple);
        mobileCompanies.add(companySamsung);
        
        /* Create an object of `Company` and set values */
        Company companyFacebook = new Company();
        companyFacebook.setId(3L);
        companyFacebook.setCompanyName("Facebook");
        
        Company companyTwitter = new Company();
        companyTwitter.setId(4L);
        companyTwitter.setCompanyName("Twitter");
        
        /**
         * - Create `List` of `Company`
         * - Add `companyFacebook` and `companyTwitter` to List.
         */
        List<Company> socialNetworkingCompanies = new ArrayList<>();
        socialNetworkingCompanies.add(companyFacebook);
        socialNetworkingCompanies.add(companyTwitter);
                
        /* Add `List` of `Companies` to Map */
        Map<String, List<Company>> companies = new HashMap<>();
        companies.put("MobileCompanies", mobileCompanies);
        companies.put("SocialNetworkingCompanies", socialNetworkingCompanies);
        
        /**
         * JavaDoc: `map` method
         * Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream
         * produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have 
         * been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)
         * 
         * Explanation: `.flatMap(key -> companies.get(key).stream())`
         * In this operation we are taking `stream` of `List<Company>` from each key of `Map<String, List<Company>>`.
         * That returns the `Stream` of `Company` objects from `stream` of `List<Company>`.
         */
        companies.keySet()
                 .stream()
                 .flatMap(key -> companies.get(key).stream())
                 .forEach(com -> {
                     System.out.println(com.getCompanyName());
                 });
    }
}

Explanation: .flatMap(key -> companies.get(key).stream())
In this operation we are taking stream of List<Company> from each key of Map<String, List<Company>>. That returns the Stream of Company objects from stream of List<Company>.


Output
Apple
Samsung
Facebook
Twitter

How to get(collect) List of Properties (String, Double, Integer) from List of beans in Java 8?

This little excerpt shows How you can fetch List<String>, List<Double>, List<Integer>, List<Object>, etc... from List<Beans>. And it also explains the use of map method in stream.

<R> Stream<R> map(Function<? super T, ? extends R> mapper);
Returns a stream consisting of the results of applying the given function to the elements of this stream.

In Simple term: map will return the stream of elements based on method you are calling.
  • public String getFirstname() : returns stream of String
  • public Double getWeight() : returns stream of Double
  • public JSONObject getMetaData : returns stream of JSONObject
  • public Employee getEmployee: returns stream of Employee

Source code (Company.java)
public class Company {
    private Long id;
    private String CompanyName;
 
 public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCompanyName() {
        return CompanyName;
    }

    public void setCompanyName(String CompanyName) {
        this.CompanyName = CompanyName;
    }
}


Source code
The above image gives you abstract idea of following code.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ListPropertiesFromBeans {
    public static void main(String[] args) {
        /* Create an object of `Company` and set values */
        Company companyGoogle = new Company();
        companyGoogle.setId(1L);
        companyGoogle.setCompanyName("Google");
        
        Company companyMicrosoft = new Company();
        companyMicrosoft.setId(2L);
        companyMicrosoft.setCompanyName("Microsoft");
       
        /**
         * - Create `List` of `Company`
         * - Add `companyGoogle` and `companyMicrosoft` to List.
         */
        List<Company> listCompanies = new ArrayList<>();
        listCompanies.add(companyGoogle);
        listCompanies.add(companyMicrosoft);

        /**
         * JavaDoc: `map` method
         * Returns a stream consisting of the results of applying the given function to the elements of this stream.
         * 
         * Explanation: `.map(Company::getCompanyName)`
         * In this operation we are calling method `getCompanyName()` on each object of `Company` in List.
         * That returns the `Stream` of value(CompanyName) of all object in List.
         * In last we are collecting that data/values in List<String>
         */
        List<String> listCompanyNames = listCompanies.stream()
                                                     .map(Company::getCompanyName)
                                                     .collect(Collectors.toList());
        
        /* Print the company name collected using `map` method */
        listCompanyNames.stream()
                        .forEach(strCompanyName -> System.out.println(strCompanyName));
    }
}

Explanation: .map(Company::getCompanyName)
In this operation we are calling method getCompanyName() on each object of Company in List. That returns the Stream of value(CompanyName[String]) of all object in List and in the last we are collecting that data/values in List<String>


Output
Google
Microsoft

How to iterate over stream and increment index value in Lambda Expression?

Lambda Expression + Java 8


Many of you having trouble for increment index value inside Lambda expression because of Local variable index defined in an enclosing scope must be final or effectively final. There is an alternative for that...

java.util.concurrent.atomic.AtomicInteger
An int value that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an java.lang.Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
Java doc

Source Code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class LambdaIncrementIndexExample {

    public static void main(String[] args) {
        /* AtomicInteger in `stream()` */
        new LambdaIncrementIndexExample().UsingStream();

        /* AtomicInteger in `parallelStream()` */
        new LambdaIncrementIndexExample().UsingParallelStream();
    }

    /**
     * Example of using AtomicInteger in `stream()`
     */
    public void UsingStream() {
        /* Create object of AtomicInteger with initial value `0` */
        AtomicInteger atomicInteger = new AtomicInteger(0);

        /* Create list of names. */
        List<String> listNames = new ArrayList<String>(Arrays.asList("Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones", "Heer Thakor"));

        listNames.stream()
                 .filter(name -> name.endsWith("Thakor"))
                 .forEach(name -> {
                    /* Get the previous value of count and increment it by `1` */
                    atomicInteger.getAndIncrement();

                    /* Print the name */
                    System.out.println(name);
                 });
  
        /* Get value of `atomicInteger` */
        System.out.println("Total match found using `stream()`: " + atomicInteger.get());
        System.out.println("+++++++++++++++++++++++++++");
    }

    /**
     * Example of using AtomicInteger in `parallelStream()`
     */
    public void UsingParallelStream() {
        /* Create object of AtomicInteger with initial value `0` */
        AtomicInteger atomicInteger = new AtomicInteger(0);

        /* Create list of names. */
        List<String> listNames = new ArrayList<String>(Arrays.asList("Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones", "Heer Thakor"));

         listNames.parallelStream()
                  .filter(name -> name.endsWith("Thakor"))
                  .forEach(name -> {
                    /* Get the previous value of count and increment it by `1` */
                    atomicInteger.getAndIncrement();

                    /* Print the name */
                    System.out.println(name);
                  });
  
        /* Get value of `atomicInteger` */
        System.out.println("Total match found using `parallelStream()`: " + atomicInteger.get());
    }
}

Output
Vicky Thakor
Chirag Thakor
Heer Thakor
Total match found using `stream()`: 3
+++++++++++++++++++++++++++
Heer Thakor
Chirag Thakor
Vicky Thakor
Total match found using `parallelStream()`: 3


Using IntStream over for loop in Java 8

Stream API Java 8

We are using for-loop since we know Java. Billions of program running based on this for-loop but time has changed. Its not just creating program that gives us desired output but your program should be faster, utilize the hardware and perform at its pick level.

Java designers did some serious changes in Java8. Lambda expression and Stream API were introduced to in Java8 and that made programmers life much more easy than ever before.

Source code (Simple for-loop)
public class ForLoopExample {

    public static void main(String[] args) {
        /* Create String array */
        String[] arrayNames = {"Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones"};

        for (int i = 0; i < arrayNames.length; i++) {
            /*Filter name which ends with "Thakor". */
            if (arrayNames[i].endsWith("Thakor")) {
                /* Print name to console. */
                System.out.println(arrayNames[i]);
            }
        }
    }
}

Output
Vicky Thakor
Chirag Thakor

Sour code (IntStream)
import java.util.stream.IntStream;

public class IntStreamExample {

    public static void main(String[] args) {
        /* Loop through Array using IntStream */
        new IntStreamExample().UsingStream();

        /* Loop through Array using IntStream with ParallelStream. */
        new IntStreamExample().UsingParallelStream();
    }

    /**
     * Loop through Array using IntStream
     */
    public void UsingStream() {
        System.out.println("Using IntStream");
        System.out.println("------------------------------------------");

        /* Create String array */
        String[] arrayNames = {"Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones"};

        /**
         * - Start loop from "range(startInclusive {initial value}, endExclusive {upper limit}}
         * - Filter data.(If condition)
         * - forEach (value that matches filter condition)
         */
        IntStream.range(0, arrayNames.length)
                 .filter(i - > arrayNames[i].endsWith("Thakor"))
                 .forEach(i - > {
                    System.out.println(arrayNames[i]);
                 });
        System.out.println("+++++++++++++++++++++++++++");
    }

    /**
     * Loop through Array using IntStream with ParallelStream.
     * Note: Use it when you want to divide your task in multiple core of CPU and order doesn't matter for the operation.
     */
    public void UsingParallelStream() {
        System.out.println("Using IntStream with ParallelStream");
        System.out.println("------------------------------------------");

        /* Create String array */
        String[] arrayNames = {"Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones"};

        /**
         * - Start loop from "range(startInclusive {initial value}, endExclusive {upper limit}}
         * - ParallelStream (Perform your task by dividing it in CPU core.) 
         * - Filter data. (If condition)
         * - forEach (value that matches filter condition)
         */
        IntStream.range(0, arrayNames.length)
                 .parallel()
                 .filter(i - > arrayNames[i].endsWith("Thakor"))
                 .forEach(i - >  {
                    System.out.println(arrayNames[i]);
                 });
        System.out.println("+++++++++++++++++++++++++++");
    }
}

Output
Using IntStream
------------------------------------------
Vicky Thakor
Chirag Thakor
+++++++++++++++++++++++++++
Using IntStream with ParallelStream
------------------------------------------
Chirag Thakor
Vicky Thakor
+++++++++++++++++++++++++++

Note:
Use ParallelStream only when you want to divide your task in multiple core of CPU and order doesn't matter for your operation.

How to convert List to Map in Java 8 using Stream API?

Code snippet demonstrate converting List<T> to Map<K,V>.

Source code(User.java)
public class User {
   private Long id;
   private String name;
 
   public Long getId() {
    return id;
   }
   public void setId(Long id) {
    this.id = id;
   }
   public String getName() {
    return name;
   }
   public void setName(String name) {
    this.name = name;
   }
}

Source code(ExampleListToMap.java)
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javaQuery.beans.User;

public class ExampleListToMap {

    public static void main(String[] args) {
        /* Creating List<String> */
        List<String> listStrings = new ArrayList<String>();
        listStrings.add("Vicky");
        listStrings.add("Thakor");

        /**
         * Convert List<String> to Map<String, String> using `stream` API
         * Explanation:
         * Collectors.toMap(String::toString, listStringName -> listStringName)
         * - String::toString => Calling `toString()` method of `String` class. 
         *                       (Note: Its compulsory to set `key` of Map from String class.)  
         * 
         * - listStringName -> listStringName => Value of Map.
         */
        Map<String, String> mapName = listStrings.stream()
                                                 .collect(Collectors.toMap(String::toString, listStringName -> listStringName));
        /* Print the Map */
        System.out.println("List<String> to Map<String, String>: " + mapName);
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++");

        /* Creating User objects */
        User objUser = new User();
        objUser.setId(1L);
        objUser.setName("Vicky Thakor");

        User objUser2 = new User();
        objUser2.setId(2L);
        objUser2.setName("Chirag Thakor");

        /* Add users to List<User> */
        List<User> listUsers = new ArrayList<User>();
        listUsers.add(objUser);
        listUsers.add(objUser2);

        /**
         * Convert List<User> to Map<Long, User> using `stream` API.
         * Explanation:
         * Collectors.toMap(User::getId, user -> user)
         * - User::getId => Calling `getter` method of `User` class. 
         *                  (Note: Its compulsory to set `key` of Map from User class.)  
         * 
         * - user -> user => Value of Map.
         */
        Map<Long, User> mapUsers = listUsers.stream().collect(Collectors.toMap(User::getId, user -> user));
  
        /* Print the Map */
        System.out.println("List<User> to Map<Long, User>:");
        mapUsers.keySet()
                .forEach(key -> {
                            User getUser = mapUsers.get(key);
                            System.out.println(key + "=" + getUser.getName());
                });
    }
}

Output
List<String> to Map<String, String>: {Vicky=Vicky, Thakor=Thakor}
+++++++++++++++++++++++++++++++++++++++++++
List<User> to Map<Long, User>:
1=Vicky Thakor
2=Chirag Thakor

Example of Collectors minBy in Lambda expression

Lambda Expression Java 8

Collectors.minBy
This static method from package java.util.stream and class Collectors used to find maximum value from given Collection. This method takes Comparator as an argument.


Source Code
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class CollectorsMinBy {

    public static void main(String[] args) {
        /* Create and add elements in List of String */
        List<String> listStrings = new ArrayList<String>();
        listStrings.add("Vicky");
        listStrings.add("Carl");
        listStrings.add("Leonard");

        /* Java 8: Use stream over List of String and use `minBy` with Comparator */
        Optional<String> optionalString = listStrings.stream()
                                                     .collect(Collectors.minBy(new Comparator<String>() {
                                                                  public int compare(String str1, String str2) {
                                                                       return str1.compareTo(str2);
                                                                  }
                                                     }));
        /* Check value is available in `Optional` */
        String resultString = optionalString.isPresent() ? optionalString.get() : "No String found";
        /* Print the resultString */
        System.out.println("Minimum String: " + resultString);

        /* Create and add elements in List of Integer */
        List<Integer> listIntegers = new ArrayList<Integer>();
        listIntegers.add(10);
        listIntegers.add(5);
        listIntegers.add(101);

        /* Java 8: Use stream over List of Integer and use `minBy` with Comparator */
        Optional<Integer> optionalInteger = listIntegers.stream()
                                                        .collect(Collectors.minBy(new Comparator<Integer>() {
                                                                     public int compare(Integer integer1, Integer integer2) {
                                                                          return integer1 - integer2;
                                                                     }
                                                        }));
        /* Check value is available in `Optional` */
        Integer resultInteger = optionalInteger.isPresent() ? optionalInteger.get() : 0;
        /* Print the resultInteger */
        System.out.println("Minimum Integer: " + resultInteger);

    }
}
Note: Don't call .get() directly on .collect(Collectors.minBy(new Comparator()) because if there is no element in List then it'll throw an exception java.util.NoSuchElementException: No value present. Always get value in Optional and check isPresent().

Output
Minimum String: Carl
Minimum Integer: 5


Example of Collectors maxBy in Lambda expression

Lambda Expression Java 8

Collectors.maxBy
This static method from package java.util.stream and class Collectors used to find maximum value from given Collection. This method takes Comparator as an argument.


Source Code
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class CollectorsMaxBy {

    public static void main(String[] args) {
        /* Create and add elements in List of String */
        List listStrings = new ArrayList<String>();
        listStrings.add("Vicky");
        listStrings.add("Carl");
        listStrings.add("Leonard");

        /* Java 8: Use stream over List of String and use `maxBy` with Comparator */
        Optional optionalString = listStrings.stream()
                                             .collect(Collectors.maxBy(new Comparator<String>() {
                                                          public int compare(String str1, String str2) {
                                                               return str1.compareTo(str2);
                                                          }
                                             }));
        /* Check value is available in `Optional` */
        String resultString = optionalString.isPresent() ? optionalString.get() : "No String found";
        /* Print the resultString */
        System.out.println("Maximum String: " + resultString);

        /* Create and add elements in List of Integer */
        List listIntegers = new ArrayList<Integer>();
        listIntegers.add(10);
        listIntegers.add(5);
        listIntegers.add(101);

        /* Java 8: Use stream over List of Integer and use `maxBy` with Comparator */
        Optional optionalInteger = listIntegers.stream()
                                               .collect(Collectors.maxBy(new Comparator<Integer>() {
                                                            public int compare(Integer integer1, Integer integer2) {
                                                                 return integer1 - integer2;
                                                            }
                                               }));
        /* Check value is available in `Optional` */
        Integer resultInteger = optionalInteger.isPresent() ? optionalInteger.get() : 0;
        /* Print the resultInteger */
        System.out.println("Maximum Integer: " + resultInteger);
    }
}
Note: Don't call .get() directly on .collect(Collectors.minBy(new Comparator()) because if there is no element in List then it'll throw an exception java.util.NoSuchElementException: No value present. Always get value in Optional and check isPresent().

Output
Maximum String: Vicky
Maximum Integer: 101