Showing posts with label Collectors. Show all posts

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