Stream sort map java

How to sort a Map in Java

In this short article, you will learn how to sort a Map in Java. This is probably one of the most frequently asked questions in Java interviews.

In Java, there are multiple ways to sort a Map, but we will focus on Java 8 Streams which is quite an elegant way of achieving this.

  1. Convert a Map into a Stream object
  2. Sort it by using Streams’ sorted() method
  3. Collect the entries and return them as a LinkedHashMap (keep the sorted order)

The sorted() method takes a Comparator as a parameter, making it possible to sort the map by any type of value.

// create a map MapString, Integer> codes = new HashMap>(); codes.put("United States", 1); codes.put("Germany", 49); codes.put("France", 33); codes.put("China", 86); codes.put("Pakistan", 92); // sort the map by keys MapString, Integer> sorted = codes.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); // print map elements sorted.entrySet().forEach(System.out::println); 
China=86 France=33 Germany=49 Pakistan=92 United States=1 

Notice the use of LinkedHashMap to store the sorted results to keep the order. By default, Collectors.toMap() returns a HashMap . The HashMap class does not provide any ordering guarantee. If we convert the sorted stream back to the HashMap , we might lose the elements ordering.

If you want to sort the Map by keys in reserve order, you only need to change the comparing order to reverse like below:

// sort the map by keys in reversed order MapString, Integer> sorted = codes.entrySet().stream() .sorted(Map.Entry.String, Integer>comparingByKey().reversed()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); 
// create a map MapString, Integer> codes = new HashMap>(); codes.put("United States", 1); codes.put("Germany", 49); codes.put("France", 33); codes.put("China", 86); codes.put("Pakistan", 92); // sort the map by values MapString, Integer> sorted = codes.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); // print map elements sorted.entrySet().forEach(System.out::println); 
United States=1 France=33 Germany=49 China=86 Pakistan=92 
// sort the map by values in reversed order MapString, Integer> sorted = codes.entrySet().stream() .sorted(Map.Entry.String, Integer>comparingByValue().reversed()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); 

The TreeMap class stores the keys in natural sorted order. It works perfect for sorting a Map by keys. All you need to do is create a TreeMap object, and push all the existing data from the HashMap into it:

// create a map MapString, Integer> codes = new HashMap>(); codes.put("United States", 1); codes.put("Germany", 49); codes.put("France", 33); codes.put("China", 86); codes.put("Pakistan", 92); // convert `HashMap` to `TreeMap` MapString, Integer> sorted = new TreeMap>(codes); // print tree elements sorted.entrySet().forEach(System.out::println); 
China=86 France=33 Germany=49 Pakistan=92 United States=1 

As you can see above, the keys (countries’ names) are sorted in a natural order. Read Next: How to sort a List using Stream sorted() in Java ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Сортировка карты по значениям в Java

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

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

TreeMap представляет собой реализацию на основе красно-черного дерева Map , который сортируется в соответствии с компаратором, переданным его конструктору. Написав пользовательский компаратор в TreeMap , мы можем отсортировать карту в соответствии с естественным порядком ее значений, как показано ниже:

// Пользовательский компаратор для сортировки карты в соответствии с естественным порядком ее значений

результат:

Sorted map by values :

Использование Guava TreeMap :

Библиотека Google Guava также предоставляет TreeMap реализацию, которую мы можем использовать для создания изменяемого пустого TreeMap instance, который сортируется в соответствии с параметром Comparator, переданным его конструктору.

2. Использование LinkedHashMap

LinkedHashMap представляет собой хэш-таблицу и реализацию связанного списка Map интерфейс с предсказуемым порядком итерации, то есть порядком, в котором значения были вставлены в карту. Мы можем использовать это свойство для создания копии карты, отсортированной в соответствии с естественным порядком ее значений.

  1. Создайте список записей карты и отсортируйте их на основе их значений.
  2. Создать пустой LinkedHashMap и для каждой записи карты в отсортированном списке вставьте в него пару ключ-значение.

Результирующий LinkedHashMap будут отсортированы по значениям.

результат:

Sorted map by values :

3. Использование Java 8

Мы также можем использовать Java 8 Stream для сортировки карты по значениям. Ниже приведены шаги:

  1. Получите поток из заданного представления сопоставлений, содержащихся в карте.
  2. Отсортируйте поток в естественном порядке значений, используя Stream.sorted() метод путем передачи компаратора, возвращаемого Map.Entry.comparingByValue() .
  3. Соберите все отсортированные элементы в LinkedHashMap с использованием Stream.collect() с Collectors.toMap() .

Обратите внимание, что поток — это последовательность элементов, а не последовательность пар ключ/значение. Итак, мы не можем построить карту из потока, не указав, как извлекать из него значения и значения. Java 8 предоставляет Collectors.toMap() метод для этой цели. Нам нужно использовать перегруженную версию toMap() который возвращает LinkedHashMap вместо HashMap чтобы сохранить отсортированный порядок.

Источник

Sort a Map by Values in Java

Simple and easy-to-understand examples of sorting Map by values, using Java 8 Stream APIs, in ascending and descending (reverse) orders. At the center of logic is the method Map.Entry.comparingByValue(), which compares the map entries in the natural order by entry values.

In Java 8, Map.Entry class has a static method comparingByValue() to help sort a Map by values. It returns a Comparator that compares Map.Entry in the natural order of values.

map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) . 

Alternatively, we can pass a custom Comparator to sort the values in a custom order. For example, we can use Comparator.reverseOrder() to sort the map in reverse order.

map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) . 

2. Java Program to Sort a Map by Values

2.1. Ascending Order or Natural Order

The following java program sorts the entries of a Map in the natural order and collects the sorted entries in a LinkedHashMap. We are collecting the entries in LinkedHashMap because it maintains the insertion order.

Map unsortedMap = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4); LinkedHashMap sortedMap = unsortedMap.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); System.out.println(sortedMap);

As discussed above, we use Comparator.reverseOrder() to sorting the Map values in reverse order.

Map unsortedMap = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4); LinkedHashMap sortedMap = unsortedMap.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); System.out.println(sortedMap);

Источник

Sort a Map using Stream and Collectors in Java

In this tutorial, I will show you how to order elements in a Map object using the Stream object and the Collectors object in Java by key and by value.

For example, we have a Map object like this:

Prior to Java 8, to sort the elements of this Map object by key, we could use the Collections.sort() static method of the Collections class:

Sort a Map using Stream and Collectors in Java

Do the same if you want to use the sort() static method of the Collections class to sort the elements in the Map object by value.

From Java 8 onwards, you have another way to use the Stream object with the Collectors object.

We will create a new Stream object from the Map object and then use the sorted() and collect() methods of this Stream object to sort.

For example, we need to order the elements of the Map object by key, we will code as follows:

. collect ( Collectors . toMap ( Map . Entry : : getKey , Map . Entry : : getValue , ( oldValue , newValue ) — > oldValue , LinkedHashMap : : new ) ) ;

Here, the sorted() method acts as an intermediate operation in the Stream pipeline. The parameter of this method is a Comparator object that allows us to define what criteria to sort. You can also use the static comparingByKey() method of the Map.Entry class to sort by key as follows:

. collect ( Collectors . toMap ( Map . Entry : : getKey , Map . Entry : : getValue , ( oldValue , newValue ) — > oldValue , LinkedHashMap : : new ) ) ;

The collect() method will act as a terminal operation in the Stream pipeline. The parameter of this method is a Collectors object and we will use the Collectors object’s toMap() method to construct a new Map object after sorting.

The Collectors object’s toMap() method has some overload methods:

toMap ( Function keyMapper , Function valueMapper , BinaryOperator mergeFunction , Supplier mapSupplier )

Where the first and second parameters of the toMap() method are instances of the Function interface used to generate keys and values for the new Map object.

The third parameter of the toMap() method is an optional parameter that is used in case the key of the new Map object has duplicate values. Using the BinaryOperator object, we can select the value of these duplicate keys, avoiding the IllegalStateException. In the above example, (oldValue, newValue) -> oldValue means that in case the key is duplicated, we will get the value of the previous key.

The final parameter of the toMap() method is also an optional parameter, which allows us to define a new Map object as a class instance. By default, if you do not use this parameter, then the class will be HashMap.

The result of this example is as follows:

Sort a Map using Stream and Collectors in Java

To order elements in a Map object by value, we can use the static comparingByValue() method of the Map.Entry object:

Источник

Читайте также:  What is console log in php
Оцените статью