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

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