Showing posts with label Collection. 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

What is the difference between List, Set and Map in Java?

List , Set , Map in Java8

List interface
An ordered collection (also known as a sequence).

Characteristics
  • Element added from 0th index, 1st, 2nd, ... nth (Sequentially).
  • List allows to insert/update/read element at specific index.
  • List allows duplicate values.
  • It maintains insertion position (1st point).
  • It allows null value.

ArrayList is one of the popular implementation of List used by programmers.

Examples


Set interface
Collection which don't allows duplicate values.

Characteristics
  • Unlike List, Set will not allow index based insert/update/read.
  • Set doesn't allow duplicate. e1 and e2 such that e1.equals(e2)
  • It doesn't maintain insertion position (unordered collection). However you can maintain order using LinkedHashSet.
  • It allows null value.

HashSet is one of the popular implementation of Set used by programmers.

Examples


Map interface
Collection to hold [KEY, VALUE] data.

Characteristics
  • Unlike List, Map will not allow index based insert/update/read.
  • Map doesn't allow duplicate KEY.
  • It doesn't maintain insertion position (unordered collection). However you can maintain order using LinkedHashMap.
  • It allows one null KEY and n number of null VALUE.

HashMap us one of the popular implementation of Map used by programmers.



Collection Framework examples in Java 8

How to convert List of data to Set of data and vice versa in Java?

Following excerpt shows how you can convert List<T> to Set<T> and Set<T> to List<T> in java.

Source code (ListToSet.java)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * List to Set example.
 *
 * @author javaQuery
 * @date 7th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ListToSet {

    public static void main(String[] args) {
        /* Create list of string */
        List<String> strings = new ArrayList<String>();
        strings.add("A");
        strings.add("B");

        Set<String> stringSet = new HashSet<String>(strings);
        /**
         * new HashSet(Collection<? extends E> c) 
         * We created Set of String so we can initialize HashSet using any collection that extends String.
         */
        
        for (String string : stringSet) {
            System.out.println(string);
        }
    }
}
You would like to read How to Initialize List in declaration?.

Source code (SetToList.java)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Set to List example.
 *
 * @author javaQuery
 * @date 7th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class SetToList {

    public static void main(String[] args) {
        /* Create set of string */
        Set<String> strings = new HashSet<String>();
        strings.add("A");
        strings.add("B");

        List<String> list = new ArrayList<>(strings);
        /**
         * new ArrayList(Collection<? extends E> c) 
         * We created List of String so we can initialize ArrayList using any collection that extends String.
         */
        
        for (String string : list) {
            System.out.println(string);
        }
    }
}
You would like to read How to Initialize Set in declaration?.

Output
A
B

How Fail Fast Iterator identifies that the collection is modified?



Image gives you the abstract idea about How iterator identifies the modification on collection. Its one of the interview question asked as sub part of Fail Fast vs Fail Safe Iterator in Java. To understand it better I pulled out the source code of HashMap.

Source code (HashMap.java)
public class HashMap<K, V>...{
    transient int modCount;

    public V put(K key, V value) {
        return this.putVal(hash(key), key, value, false, true);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        ...
        ++this.modCount;
        ...
    }
 
    public Set<Map.Entry<K,V>> entrySet() {
        // this method internally uses HashIterator
    }

    abstract class HashIterator{
        int expectedModCount;  // for fast-fail
        ...
        HashIterator() {
            expectedModCount = modCount;
            ...
        }
 
        final Node nextNode() {
            ...
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            ...
            ...
        }
    }
}
So when you call method entrySet() of HashMap, It creates the object of inner class HashIterator with current value of modCount and set it in expectedModCount.

Now when nextNode() method is called it compares value of expectedModCount with parent class's (HashMap) modCount and if its not same then it throws ConcurrentModificationException.

Source code (FailFastExample.java)
/**
 * Example of Fail Fast using Map.
 * @author javaQuery
 * @date 4th August, 2016
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailFastExample {
    public static void main(String[] args) {
        Map<String, Double> carPrice = new HashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for(Map.Entry<String, Double> car : carPrice.entrySet()){
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());
            
            /* Will cause java.util.ConcurrentModificationException */
            carPrice.put("Lamborghini", 300000D);
        }
    }
}

Output
Car: Ferrari
Price: 200000.0
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
 at com.javaquery.collections.map.FailFastExample.main(FailFastExample.java:23)

Fail Fast vs Fail Safe Iterator in Java

Fail Fast vs Fail Safe


One of the popular interview question asked to java developer. To know how well you understand the iterator.

Fail Fast
When you perform add, update or remove on collection while iterating on it. It throws java.util.ConcurrentModificationException.

Source code (FailFastExample.java)
import java.util.HashMap;
import java.util.Map;

/**
 * Example of Fail Fast using Map.
 * @author javaQuery
 * @date 4th August, 2016
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailFastExample {
    public static void main(String[] args) {
        Map<String, Double> carPrice = new HashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for(Map.Entry<String, Double> car : carPrice.entrySet()){
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());
            
            /* Will cause java.util.ConcurrentModificationException */
            carPrice.put("Lamborghini", 300000D);
        }
    }
}

Output
Car: Ferrari
Price: 200000.0
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
 at com.javaquery.collections.map.FailFastExample.main(FailFastExample.java:23)

You can also consider Collection (List, Set, Map) shared between two or more Threads. One is iterating on collection and other tries to add element in it then the thread iterating over it, will throw java.util.ConcurrentModificationException

In interview if you are able to answer this question. They might me interested in checking your knowledge little bit deep. You may face the question How Fail Fast Iterator identifies that the collection is modified?

Fail Safe
It iterate over the clone(copy) of original collection. So It won't throw java.util.ConcurrentModificationException.

Source code (FailSafeExample.java)
/**
 * Example of Fail Safe using ConcurrentHashMap.
 * @author javaQuery
 * @date 4th August, 2016 
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailSafeExample {

    public static void main(String[] args) {
        Map<String, Double> carPrice = new ConcurrentHashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for (Map.Entry<String, Double> car : carPrice.entrySet()) {
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());

            /* Will be added in original copy of Map but won't available in Iterator */
            carPrice.put("Lamborghini", 300000D);
        }
        System.out.println("=== loop finished ===");
        System.out.println("Car: Lamborghini" + ", Price: " + carPrice.get("Lamborghini"));
    }
}

Output
Car: Ferrari
Price: 200000.0
Car: Porsche
Price: 100000.0
=== loop finished ===
Car: Lamborghini, Price: 300000.0

How to Initialize Set in declaration?

Following excerpt show How you can Initialize Set in its declaration.

Source code
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author javaQuery
 * @date 29th October, 2015
 * Initialize Set in its declaration.
 */
public class InitializeSetExample {
    public static void main(String[] args) {
        /* Declare and Initialize Set of Integer */
        Set<Integer> setIntegers = new HashSet<Integer>(Arrays.asList(10, 20, 30));
        
        System.out.println("Print value of Set<Integer>");
        /* Print value of Set */
        for (Integer integer : setIntegers) {
            System.out.println(integer);
        }
        
        /* Declare and Initialize Set of String */
        Set<String> setStrings = new HashSet<>(Arrays.asList("Chirag", "Yogita", "Vicky", "Heer"));
        
        System.out.println("Print value of Set<String>");
        /* Print value of Set */
        for (String string : setStrings) {
            System.out.println(string);
        }
    }
}

Output
Print value of Set<Integer>
20
10
30
Print value of Set<String>
Vicky
Heer
Chirag
Yogita

Reference
How to Initialize List in declaration?

How to Initialize List in declaration?

Following excerpt show How you can Initialize List in its declaration.

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

/**
 * @author javaQuery
 * @date 29th October, 2015 Initialize List in its declaration.
 */
public class InitializeListExample {

    public static void main(String[] args) {
        /* Declare and Initialize List of Integer */
        List<Integer> listIntegers = new ArrayList<Integer>(Arrays.asList(10, 20, 30));

        System.out.println("Print value of List<Integer>");
        /* Print value of List */
        for (Integer integer : listIntegers) {
            System.out.println(integer);
        }

        /* Declare and Initialize List of String */
        List<String> listStrings = new ArrayList<String>(Arrays.asList("Chirag", "Yogita", "Vicky", "Heer"));

        System.out.println("Print value of List<String>");
        /* Print value of List */
        for (String string : listStrings) {
            System.out.println(string);
        }
    }
}

Output
Print value of List<Integer>
10
20
30
Print value of List<String>
Chirag
Yogita
Vicky
Heer

Reference
How to Initialize Set in declaration?

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 get Unique values from List of String?


This is frequently asked question in Java Interviews for Collection Framework. Question asked to know the basic knowledge of Interviewee.

Source code
public class GetUniqueValuesFromList {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add element from 0th position */
        listString.add("vicky");
        listString.add("chirag");
        listString.add("heer");
        listString.add("riddhi");
        listString.add("chirag");
        
        System.out.println("Initial String List:" + listString);
        System.out.println("------------------------");
        
        /* Create set of String from List */
        /* Set will store only unique values from listString */
        Set<String> setString = new HashSet<String>(listString);
        
        System.out.println("Values in Set:" + setString);
        System.out.println("------------------------");
        
        /* Clear the listString */
        listString.clear();
        
        /* Add setString(Unique) values back to listString */
        listString.addAll(setString);
        
        System.out.println("Unique values in List" + listString);
    }
}

Output
Initial String List:[vicky, chirag, heer, riddhi, chirag]
------------------------
Values in Set:[vicky, riddhi, heer, chirag]
------------------------
Unique values in List[vicky, riddhi, heer, chirag]

How to check is there any common element between two List of String?

Java Collection Framework disjoint


Collections.disjoint(Collection<?> c1, Collection<?> c2)
Returns true if the two specified collections have no elements in common.

Source Code
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author javaQuery
 */
public class DisjointExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add elements in listString */
        listString.add("a");
        listString.add("b");
        listString.add("c");

        /* Create list of String */
        List<String> listStringSecond = new ArrayList<String>();
        /* Add elements in listString */
        listStringSecond.add("x");
        listStringSecond.add("y");
        listStringSecond.add("z");

        System.out.println("Initial List 1: " + listString);
        System.out.println("Initial List 2: " + listStringSecond);
        System.out.println("------------------------");
        System.out.println("Disjoint: " + Collections.disjoint(listString, listStringSecond));

        /* Add element available in listString */
        listStringSecond.add("a");
        System.out.println("------------------------");
        System.out.println("List 2 after add(\"a\"): " + listStringSecond);
        System.out.println("Disjoint after add(\"a\"): " + Collections.disjoint(listString, listStringSecond));
    }
}

Output
Initial List 1: [a, b, c]
Initial List 2: [x, y, z]
------------------------
Disjoint: true
------------------------
List 2 after add("a"): [x, y, z, a]
Disjoint after add("a"): false

How to reverse List in Java Collection Framework?

Collections Framework Reverse Java


List allows to add String and Custom bean elements in it. To reverse the given list we can use Collections.reverse(List<?> list).

Source Code
/**
 * @author javaQuery
 */
public class User{

    private String Firstname;
    private String Lastname;

    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;
    }
}
import com.javaquery.beans.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author javaQuery
 */
public class ReverseListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add elements in listString */
        listString.add("a");
        listString.add("b");
        listString.add("c");

        System.out.println("Initial List");
        System.out.println(listString);
        System.out.println("------------------------");

        Collections.reverse(listString);
        System.out.println("Reverse List");
        System.out.println(listString);
        System.out.println("------------------------");

        /* Create object of User */
        User user1 = new User();
        /* Set Firstname of User */
        user1.setFirstname("Vicky");
        /* Set Lastname of User */
        user1.setLastname("Thakor");

        User user2 = new User();
        user2.setFirstname("Chirag");
        user2.setLastname("Thakor");

        User user3 = new User();
        user3.setFirstname("Heer");
        user3.setLastname("Thakor");
        
        /* Add Users in List<User> */
        List<User> listUser = new ArrayList<User>();
        /* Add elements in listUser */
        listUser.add(user1);
        listUser.add(user2);
        listUser.add(user3);

        System.out.println("Initial List");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
        System.out.println("------------------------");
        System.out.println("Reverse List");
        System.out.println("------------------------");
        Collections.reverse(listUser);
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }        
    }
}

Output
[a, b, c]
------------------------
Reverse List
[c, b, a]
------------------------
Initial List
------------------------
Vicky Thakor
Chirag Thakor
Heer Thakor
------------------------
Reverse List
------------------------
Heer Thakor
Chirag Thakor
Vicky Thakor

How to sort List of Bean in Java?

Collection Framework Sort


In my previous article How to sort a List in Java? We have seen how we can sort List<String>. This time we'll understand code of How we can sort List<Bean>.

Storing data in bean is common practice in current industry. Bean structure allows us to get specific property of object. Hope you all are aware of what is bean so lets not waste time and understand the code.

Background
We have User object that holds two property Firstname and Lastname. We will sort the List on Firstname in ascending order. There are two technique you can use to sort an object and we'll checkout one by one.

Technique One
Say you have access to your bean class and can modify the class file then by implementing Comparable interface you can perform sorting.
/**
 * @author javaQuery
 */
public class User implements Comparable<User> {

    private String Firstname;
    private String Lastname;

    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;
    }

    /**
     * This `compareTo` used to compare two `User` object,
     * Which internally uses `compareTo` of String class to compare two String values.
     * @param obj
     * @return 
     */
    @Override
    public int compareTo(User obj) {
        /* Check object and Firstname are not null */
        if(obj != null && obj.Firstname != null){
            /* We will use `compareTo` of String class */
            /* For ascending order */
            return this.Firstname.compareTo(obj.Firstname);
   
            /* For descending order */
            /* return obj.Firstname.compareTo(this.Firstname) */
        }else{
            return -1;
        }
    }
 
 /* If you want to sort on `int` value then uncomment following code */
//   @Override
//    public int compareTo(User obj) {
//        /* Check object and id is not null and 0 */
//        if (obj != null && obj.getId() != 0) {
//            /* For ascending order */
//            return this.getId() - obj.getId();
//
//            /* For descending order */
//            /* return obj.getId() - this.getId(); */
//        } else {
//            return -1;
//        }
//    }
}
Source Code
import com.javaquery.beans.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author javaQuery
 */
public class SortingObjectListExample {

    public static void main(String[] args) {
        /* Create object of User */
        User user1 = new User();
        /* Set Firstname of User */
        user1.setFirstname("Vicky");
        /* Set Lastname of User */
        user1.setLastname("Thakor");

        User user2 = new User();
        user2.setFirstname("Chirag");
        user2.setLastname("Thakor");

        User user3 = new User();
        user3.setFirstname("Heer");
        user3.setLastname("Thakor");

        User user4 = new User();
        user4.setFirstname("Yogita");
        user4.setLastname("Thakor");

        User user5 = new User();
        user5.setFirstname("Riddhi");
        user5.setLastname("Thakor");

        User user6 = new User();
        user6.setFirstname("Xender");
        user6.setLastname("Thakor");

        /* Add Users in List<User> */
        List<User> listUser = new ArrayList<User>();
        listUser.add(user4);
        listUser.add(user6);
        listUser.add(user1);
        listUser.add(user5);
        listUser.add(user2);
        listUser.add(user3);

        System.out.println("Initial List");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
        System.out.println("------------------------");

        Collections.sort(listUser);
        System.out.println("List after Collections.sort(List<T> list)");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
    }
}
Output of the above code is given at the end of the article as both technique gives same output.

Technique Two
Say if you don't have access to your bean(bind in jar) and still you want to sort on specific property then by creating custom Comparator you can achieve same.
/**
 * @author javaQuery
 */
public class User{

    private String Firstname;
    private String Lastname;

    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;
    }
}
Source code
import com.javaquery.beans.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author javaQuery
 */
public class SortingObjectListExample {

    public static void main(String[] args) {
        /* Create object of User */
        User user1 = new User();
        /* Set Firstname of User */
        user1.setFirstname("Vicky");
        /* Set Lastname of User */
        user1.setLastname("Thakor");

        User user2 = new User();
        user2.setFirstname("Chirag");
        user2.setLastname("Thakor");

        User user3 = new User();
        user3.setFirstname("Heer");
        user3.setLastname("Thakor");

        User user4 = new User();
        user4.setFirstname("Yogita");
        user4.setLastname("Thakor");

        User user5 = new User();
        user5.setFirstname("Riddhi");
        user5.setLastname("Thakor");

        User user6 = new User();
        user6.setFirstname("Xender");
        user6.setLastname("Thakor");

        /* Add Users in List<User> */
        List<User> listUser = new ArrayList<User>();
        listUser.add(user4);
        listUser.add(user6);
        listUser.add(user1);
        listUser.add(user5);
        listUser.add(user2);
        listUser.add(user3);

        System.out.println("Initial List");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
        System.out.println("------------------------");

        /* Create object of `SortingObjectListExample` */
        SortingObjectListExample objSortingObjectListExample = new SortingObjectListExample();
        /* Get custom Comparator */
        Comparator<User> objComparator = objSortingObjectListExample.getComparator();

        /* Sort List<User> using custom Comparator */
        Collections.sort(listUser, objComparator);
        System.out.println("List after Collections.sort(List<T> list)");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
    }

    /* Create custom Comparator */
    public Comparator<User> getComparator() {
        return new Comparator<User>() {

            @Override
            public int compare(User obj1, User obj2) {
                /* Check obj1 and obj2 are not null and also check Firstname of both objects are not null */
                if (obj1 != null && obj2 != null
                        && obj1.getFirstname() != null && obj2.getFirstname() != null) {
                    /* Use `compareTo` of String class to compare two String values */
                    /* For ascending order */
                    return obj1.getFirstname().compareTo(obj2.getFirstname());
   
                    /* For descending order */
                    /* return obj2.getFirstname().compareTo(obj1.getFirstname()) */
                } else {
                    return -1;
                }
            }
        };
    }
}
Output
Initial List
------------------------
Yogita Thakor
Xender Thakor
Vicky Thakor
Riddhi Thakor
Chirag Thakor
Heer Thakor
------------------------
List after Collections.sort(List<T> list)
------------------------
Chirag Thakor
Heer Thakor
Riddhi Thakor
Vicky Thakor
Xender Thakor
Yogita Thakor

How to compare two List of String in Java?

List: Collections Framework Java


The best approach to compare two List<String>

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

/**
 * @author javaQuery
 */
public class CompareTwoListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString1 = new ArrayList<String>();
        /* Add element from 0th position */
        listString1.add("a");
        listString1.add("b");
        listString1.add("c");
        listString1.add("d");
        listString1.add("e");

        /* Print list */
        System.out.println("Initial List1:\n" + listString1);
        System.out.println("---------------------------------");

        /* Create list of String */
        List<String> listString2 = new ArrayList<String>();
        /* Add element from 0th position */
        listString2.add("e");
        listString2.add("d");
        listString2.add("c");
        listString2.add("a");
        listString2.add("b");
        
        /* Print list */
        System.out.println("Initial List2:\n" + listString2);
        System.out.println("---------------------------------");

        if(listString1 != null && listString2 != null && (listString1.size() == listString2.size())){
            listString1.removeAll(listString2);
            if(listString1.isEmpty()){
                System.out.println("Both list are same.");
            }else{
                System.out.println("Both list are not same");
            }
        }
    }
}

Output
Initial List1:
[a, b, c, d, e]
---------------------------------
Initial List2:
[e, d, c, a, b]
---------------------------------
Both list are same.

How to remove all elements from List except specific?

Collection Framework Java

retainAll(Collection<?> c)
Retains only the elements in this list that are contained in the specified collection. In other words, removes elements from list which is not available in specified list.

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

/**
 * @author javaQuery
 */
public class RetainListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add element from 0th position */
        listString.add("a");
        listString.add("b");
        listString.add("c");
        listString.add("d");
        listString.add("e");

        /* Print list */
        System.out.println("Initial List:\n" + listString);
        System.out.println("---------------------------------");

        /* Create another list of String */
        List<String> retainList = new ArrayList<String>();
        /* Add elements that you want to keep in final List */
        retainList.add("b");
        retainList.add("d");

        /* Call `retainAll(Collection<?> c)` and pass list of item you want to keep */
        listString.retainAll(retainList);

        /* Print list */
        System.out.println("List after retainAll(Collection<?> c):\n" + listString);
    }
}

Output
Initial List:
[a, b, c, d, e]
---------------------------------
List after retainAll(Collection<?> c):
[b, d]

How to convert List to Array in Java?

List to Array Collections Framework


Using List over regular Array is the best practice in Java. However in certain situations we have to convert List to Array. There are two versions of toArray() is available. Lets understand one after another.

When we need to convert Array to List?
  • Method is not overloaded to support collection. (i.e Available only MyMethod(String[] str) not MyMethod(List listStr))
  • Passing an Array to a method in other API or framework.

toArray()
This will return an Array of Object[].

T[] toArray(T[] a)
This will return an Array of given data type T[]. This is much more convenient to use. This conversion has different scenarios while converting to Array.

  1. Same size of Array: When you have Array of same size of List, It will convert normally.
  2. Less size of Array: When you have Array has less size of List, It'll increase the size of Array.
  3. Greater size of Array: When you have Array with greater size of List, The element in the array immediately following the end of the list is set to null. (JAVADOC: This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)

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

/**
 * @author javaQuery
 */
public class ListToArrayExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add element from 0th position */
        listString.add("a");
        listString.add("b");
        listString.add("c");

        /* Get an Array of Object */
        Object[] obj = listString.toArray();
        /* Loop through all elements */
        for (Object object : obj) {
            /* Check object is instanceof String */
            if (object instanceof String) {
                System.out.println(object.toString());
            }
        }
        System.out.println("---------------------------------");
        System.out.println("An array of same size of List");
        /* Create an array of String */
        String[] arrayString = new String[listString.size()];
        /* Get Array of String */
        arrayString = listString.toArray(arrayString);
        /* Loop through all elements */
        for (String str : arrayString) {
            System.out.println(str);
        }
        
        System.out.println("---------------------------------");
        System.out.println("An array of less size than List(*T[] toArray(T[] a) will increase the size of Array)");
        /* Create an array of String */
        String[] arrayStringLessSize = new String[2];
        /* Get Array of String */
        arrayStringLessSize = listString.toArray(arrayStringLessSize);
        /* Loop through all elements */
        for (String str : arrayStringLessSize) {
            System.out.println(str);
        }
        
        System.out.println("---------------------------------");
        System.out.println("An array of greater size than List");
        System.out.println("(T[] toArray(T[] a): The element in the array immediately following the end of the list is set to null)");
        /* Create an array of String */
        String[] arrayStringGreaterSize = new String[5];
        arrayStringGreaterSize[3] = "x";
        arrayStringGreaterSize[4] = "y";
        System.out.println("** Array before T[] toArray(T[] a) **");
        /* Loop through all elements */
        for (String str : arrayStringGreaterSize) {
            System.out.println(str);
        }
        
        /* Get Array of String */
        arrayStringGreaterSize = listString.toArray(arrayStringGreaterSize);
        System.out.println("** Array after T[] toArray(T[] a) **");
        /* Loop through all elements */
        for (String str : arrayStringGreaterSize) {
            System.out.println(str);
        }
    }
}

Output
a
b
c
---------------------------------
An array of same size of List
a
b
c
---------------------------------
An array of less size than List(*T[] toArray(T[] a) will increase the size of Array)
a
b
c
---------------------------------
An array of greater size than List
(T[] toArray(T[] a): The element in the array immediately following the end of the list is set to null)
** Array before T[] toArray(T[] a) **
null
null
null
x
y
** Array after T[] toArray(T[] a) **
a
b
c
null
y