Java map from entryset

Using Streams with Map in Java 8

Java 8 stream is widely used feature to write code in functional programming way. In this tutorial, we’ll discuss how to use Streams for Map creation, iteration and sorting.

Let’s create a User class and List of users, which we will use in all the examples of this tutorial:-

 class User   Long id;  String name;  Integer age;   // constructor, getters, setters, toString  >  ListUser> users = List.of(new User(1L, "Andrew", 23),  new User(2L, "Billy", 42),  new User(3L, "David", 29),  new User(4L, "Charlie", 30),  new User(5L, "Andrew", 18),  new User(6L, "Charlie", 19)); 

Please note that user id is unique and user name is not unique. You can see multiple users with name i.e. Andrew and Charlie. We have kept them intentionally to be used in our examples.

Create a Map

A Map is created, when you collect a stream of elements using either Collectors.toMap() or Collectors.groupingBy() .

using Collectors.toMap()

Example 1: Map from streams having unique key

Let’s stream the List and collect it to a Map using Collectors.toMap(keyMapper, valueMapper) where key is unique id of user and value is name of the user which may duplicate:-

MapLong, String> map = users.stream()  .collect(Collectors.toMap(User::getId, User::getName));  // 

Another example to create a Map using unique user id as key and user object as value:-

MapLong, User> map = users.stream()  .collect(Collectors.toMap(User::getId, Function.identity()));  //, // 2=User, // 3=User, // 4=User, // 5=User, // 6=User> 
Example 2: Map from streams having duplicate key

In previous examples, we used user id as key which perfectly works because key of a Map should be unique.

duplicate key results error!

Let’s see what happens when we use user name as a key which is not unique and user age as value:-

MapString, Integer> map = users.stream()  .collect(Collectors.toMap(User::getName, User::getAge)); 

It throws IllegalStateException which is expected since key of a Map should be unique

java.lang.IllegalStateException: Duplicate key Andrew (attempted merging values 23 and 18) 
mergeFunction to the rescue!

Java 8 Streams provide Collectors.toMap(keyMapper, valueMapper, mergeFunction) overloaded method where you can specify which value to consider when duplicate key issue occur.

Let’s collect a Map having user name as a key, merge function indicate that keep the old value for the same key:-

MapString, Integer> idValueMap = users.stream()  .collect(Collectors.toMap(User::getName, User::getAge, (oldValue, newValue) -> oldValue));  // 

We don’t see any error this time and a Map is created with unique user names. Duplicate user names are merged having age value whichever comes first in the list.

Example 3: ConcurrentHashMap, LinkedHashMap, and TreeMap from streams

Java 8 Streams provide Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapFactory) overloaded method where you can specify the type using mapFactory to return ConcurrentHashMap, LinkedHashMap or TreeMap.

 MapString, Integer> concurrentHashMap = users.stream()  .collect(Collectors.toMap(User::getName, User::getAge, (o1, o2) -> o1, ConcurrentHashMap::new));   MapString, Integer> linkedHashMap = users.stream()  .collect(Collectors.toMap(User::getName, User::getAge, (o1, o2) -> o1, LinkedHashMap::new));   MapString, Integer> treeMap = users.stream()  .collect(Collectors.toMap(User::getName, User::getAge, (o1, o2) -> o1, TreeMap::new)); 

using Collectors.groupingBy()

A Map is returned, when you group a stream of objects using Collectors.groupingBy(keyMapper, valueMapper) . You can specify the key and value mapping function. Specifying the value mapping function is optional and it returns a List by default.

Example 1: Group the stream by Key

Let’s group the stream of user object by name using Collectors.groupingBy(keyMapper) which returns a Map having key as user name and value as List of user object matching that key:-

MapString, ListUser>> groupByName = users.stream()  .collect(Collectors.groupingBy(User::getName));  // ], // Andrew=[User, User], // Charlie=[User, User], // David=[User]> 
Example2: Group the stream by key and value

This time we will specify both key and value mapping function in Collectors.groupingBy(keyMapper, valueMapper) . For example:-

Count the users having the same name, where key is user name and value is count:-

 MapString, Long> countByName = users.stream()  .collect(Collectors.groupingBy(User::getName, Collectors.counting()));  // 

Sum of the age of users having the same name, where key is user name and value is sum of age:-

MapString, Integer> sumAgeByName = users.stream()  .collect(Collectors.groupingBy(User::getName, Collectors.summingInt(User::getAge)));  // 

Iterate through Map

There are three ways to iterate through a Map:-

Using keySet()

The method keySet() is applied on Map which returns Set and can be streamed to iterate through keys:-

users.stream()  .collect(Collectors.toMap(User::getId, User::getName))  .keySet()  .stream()  .forEach(System.out::print);  // Prints "1 2 3 4 5" 

Using values()

The method values() is applied on Map which returns Collection and can be streamed to iterate through values:-

users.stream()  .collect(Collectors.toMap(User::getId, User::getName))  .values()  .stream()  .forEach(System.out::print);  // Prints "Andrew Billy David Charlie Andrew Charlie" 

Using entrySet()

The method entrySet() is applied on Map which returns Set> and can be streamed to iterate through entries (keys & values):-

users.stream()  .collect(Collectors.toMap(User::getId, User::getName))  .entrySet()  .stream()  .forEach(System.out::print);  // Prints "1=Andrew 2=Billy 3=David 4=Charlie 5=Andrew 6=Charlie" 

Sort the Map

By Key

We can sort the Map by key using streams with built-in comparator Map.Entry.comparingByKey()

Sort the Map by key in alphabetical order and print it:-

users.stream()  .collect(Collectors.toMap(User::getName, User::getAge, (o1,o2) -> o1))  .entrySet()  .stream()  .sorted(Map.Entry.comparingByKey())  .forEach(System.out::println);  // Andrew=23 // Billy=42 // Charlie=30 // David=29 

Sort the Map by key in reverse alphabetical order and collect to LinkedHashMap:-

MapString, Integer> sortByKeyReverse = users.stream()  .collect(Collectors.toMap(User::getName, User::getAge, (o1,o2) -> o1))  .entrySet()  .stream()  .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1,o2) -> o1, LinkedHashMap::new));  // 

By Value

We can sort the Map by value using streams with built-in comparator Map.Entry.comparingByValue()

Sort the Map by value in ascending order and print it:-

users.stream()  .collect(Collectors.toMap(User::getName, User::getAge, (o1,o2) -> o1))  .entrySet()  .stream()  .sorted(Map.Entry.comparingByValue()).forEach(System.out::println);  // Andrew=23 // David=29 // Charlie=30 // Billy=42 

Sort the Map by value in descending order and collect to LinkedHashMap:-

MapString, Integer> sortByValueReverse = users.stream()  .collect(Collectors.toMap(User::getName, User::getAge, (o1,o2) -> o1))  .entrySet()  .stream()  .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1,o2) -> o1, LinkedHashMap::new));  // 

By Both Key and Value

We can sort the Map by using both key and value one after another using thenComparing()

Sort the Map by value in alphabetical order and then sort by key in descending order and collect to LinkedHashMap:-

ComparatorMap.EntryLong, String>> valueComparator = Map.Entry.comparingByValue(); ComparatorMap.EntryLong, String>> keyComparator = Map.Entry.comparingByKey(Comparator.reverseOrder());  MapLong, String> sortByValueThenKey = users.stream()  .collect(Collectors.toMap(User::getId, User::getName))  .entrySet()  .stream()  .sorted(valueComparator.thenComparing(keyComparator))  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));  // 

We got a sorted Map having user names sorted in alphabetical order first and then keys are sorted in descending order of user id.

See Also

Ashish Lahoti avatar

Ashish Lahoti is a Software Engineer with 12+ years of experience in designing and developing distributed and scalable enterprise applications using modern practices. He is a technology enthusiast and has a passion for coding & blogging.

Источник

Итерация карты в Java с использованием метода entrySet()

В этом посте будут обсуждаться различные методы итерации карты в Java с использованием entrySet() метод.

Мы знаем это Map.entrySet() возвращает набор сопоставлений ключ-значение, содержащихся в карте. Итак, мы можем перебрать карту, используя Map.entrySet() , который содержит обе пары ключ-значение. Есть несколько способов сделать это:

1. Использование Iterator

Поскольку карта не расширяет Collection интерфейс, у него нет собственного итератора. Но Map.entrySet() возвращает набор сопоставлений ключ-значение, и поскольку Set расширяет Collection интерфейс, мы можем получить к нему итератор. Теперь мы можем легко обработать каждую пару ключ-значение, используя простой цикл while, как показано ниже:

2. Использование цикла for-each (расширенный оператор for)

Цикл for также имеет другую вариацию, предназначенную для итерации по коллекциям и массивам. Он называется циклом for-each и доступен любому объекту, реализующему цикл. Iterable интерфейс. В качестве Set расширяет Collection интерфейс и Collection расширяет Iterable интерфейс, мы можем использовать цикл for-each для прохода через entrySet. Обратите внимание, что этот подход также вызовет iterator() метод за кадром.

3. Использование Iterator.forEachRemaining() метод

Мы также можем использовать forEachRemaining() метод, который является последним дополнением к Iterator интерфейс в Java 8 и выше. Он выполняет данное действие для каждого оставшегося элемента, пока все элементы не будут обработаны.

Как было показано ранее, мы можем легко получить итератор для множества Map.Entry . Когда у нас есть итератор, мы можем передать ссылку на метод System.out::println или соответствующее лямбда-выражение E -> System.out.println(E) к forEachRemaining() метод, как показано ниже:

Источник

Читайте также:  Тег TABLE, атрибут bgcolor
Оцените статью