- Сортировка карты по значениям в Java
- 1. Использование TreeMap
- 2. Использование LinkedHashMap
- 3. Использование Java 8
- Sort a Map by Values in Java
- How to Sort a HashMap by Value in Java?
- Sorting HashMap by Value Simple Example
- Another Example of Sorting HashMap by Value
- Sorting the HashMap using a custom comparator
- Conclusion
Сортировка карты по значениям в Java
В этом посте будут обсуждаться различные методы сортировки карты по значениям в Java, т. е. сортировка карты в соответствии с естественным порядком ее значений.
1. Использование TreeMap
TreeMap представляет собой реализацию на основе красно-черного дерева Map , который сортируется в соответствии с компаратором, переданным его конструктору. Написав пользовательский компаратор в TreeMap , мы можем отсортировать карту в соответствии с естественным порядком ее значений, как показано ниже:
// Пользовательский компаратор для сортировки карты в соответствии с естественным порядком ее значений
результат:
Sorted map by values :
Использование Guava TreeMap :
Библиотека Google Guava также предоставляет TreeMap реализацию, которую мы можем использовать для создания изменяемого пустого TreeMap instance, который сортируется в соответствии с параметром Comparator, переданным его конструктору.
2. Использование LinkedHashMap
LinkedHashMap представляет собой хэш-таблицу и реализацию связанного списка Map интерфейс с предсказуемым порядком итерации, то есть порядком, в котором значения были вставлены в карту. Мы можем использовать это свойство для создания копии карты, отсортированной в соответствии с естественным порядком ее значений.
- Создайте список записей карты и отсортируйте их на основе их значений.
- Создать пустой LinkedHashMap и для каждой записи карты в отсортированном списке вставьте в него пару ключ-значение.
Результирующий LinkedHashMap будут отсортированы по значениям.
результат:
Sorted map by values :
3. Использование Java 8
Мы также можем использовать Java 8 Stream для сортировки карты по значениям. Ниже приведены шаги:
- Получите поток из заданного представления сопоставлений, содержащихся в карте.
- Отсортируйте поток в естественном порядке значений, используя Stream.sorted() метод путем передачи компаратора, возвращаемого Map.Entry.comparingByValue() .
- Соберите все отсортированные элементы в 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);
How to Sort a HashMap by Value in Java?
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
HashMap in java provides quick lookups. They store items in “key, value” pairs. To get a value from the HashMap, we use the key corresponding to that entry. HashMaps are a good method for implementing Dictionaries and directories. Key and Value can be of different types (eg — String, Integer). We can sort the entries in a HashMap according to keys as well as values. In this tutorial we will sort the HashMap according to value. The basic strategy is to get the values from the HashMap in a list and sort the list. Here if the data type of Value is String, then we sort the list using a comparator. To learn more about comparator, read this tutorial. Once we have the list of values in a sorted manner, we build the HashMap again based on this new list. Let’s look at the code.
Sorting HashMap by Value Simple Example
We first get the String values in a list. Then we sort the list. To sort the String values in the list we use a comparator. This comparator sorts the list of values alphabetically.
Collections.sort(list, new ComparatorString>() public int compare(String str, String str1) return (str).compareTo(str1); > >);
Once, we have sorted the list, we build the HashMap based on this sorted list. The complete code is as follows :
package com.journaldev.collections; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; public class Main public static void main(String[] args) HashMapString, String> map = new HashMap>(); LinkedHashMapString, String> sortedMap = new LinkedHashMap>(); ArrayListString> list = new ArrayList>(); map.put("2", "B"); map.put("8", "A"); map.put("4", "D"); map.put("7", "F"); map.put("6", "W"); map.put("19", "J"); map.put("1", "Z"); for (Map.EntryString, String> entry : map.entrySet()) list.add(entry.getValue()); > Collections.sort(list, new ComparatorString>() public int compare(String str, String str1) return (str).compareTo(str1); > >); for (String str : list) for (EntryString, String> entry : map.entrySet()) if (entry.getValue().equals(str)) sortedMap.put(entry.getKey(), str); > > > System.out.println(sortedMap); > >
HashMap entries are sorted according to String value.
Another Example of Sorting HashMap by Value
package com.JournalDev; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; public class Main public static void main(String[] args) HashMapString, Integer> map = new HashMap>(); LinkedHashMapString, Integer> sortedMap = new LinkedHashMap>(); ArrayListInteger> list = new ArrayList>(); map.put("A", 5); map.put("B", 7); map.put("C", 3); map.put("D", 1); map.put("E", 2); map.put("F", 8); map.put("G", 4); for (Map.EntryString, Integer> entry : map.entrySet()) list.add(entry.getValue()); > Collections.sort(list); for (int num : list) for (EntryString, Integer> entry : map.entrySet()) if (entry.getValue().equals(num)) sortedMap.put(entry.getKey(), num); > > > System.out.println(sortedMap); > >
Here HashMap values are sorted according to Integer values.
Sorting the HashMap using a custom comparator
If you notice the above examples, the Value objects implement the Comparator interface. Let’s look at an example where our value is a custom object. We can also create a custom comparator to sort the hash map according to values. This is useful when your value is a custom object. Let’s take an example where value is a class called ‘Name’. This class has two parameters, firstName and lastName. The code for class Name is :
package com.JournalDev; public class Name String firstName; String lastName; Name(String a, String b) firstName=a; lastName=b; > public String getFirstName() return firstName; > >
ComparatorName> byName = (Name obj1, Name obj2) -> obj1.getFirstName().compareTo(obj2.getFirstName());
We are sorting the names according to firstName, we can also use lastName to sort. Rather than using a list to get values from the map, we’ll be using LinkedHashMap to create the sorted hashmap directly. The complete code is :
public static void main(String[] args) HashMapInteger, Name> hmap = new HashMapInteger, Name>(); Name name1 = new Name("Jayant", "Verma"); Name name2 = new Name("Ajay", "Gupta"); Name name3 = new Name("Mohan", "Sharma"); Name name4 = new Name("Rahul", "Dev"); hmap.put(9, name1); hmap.put(1, name2); hmap.put(6, name3); hmap.put(55, name4); ComparatorName> byName = (Name obj1, Name obj2) -> obj1.getFirstName().compareTo(obj2.getFirstName()); LinkedHashMapInteger, Name> sortedMap = hmap.entrySet().stream() .sorted(Map.Entry.Integer, Name>comparingByValue(byName)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); //printing the sorted hashmap Set set = sortedMap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) Map.Entry me2 = (Map.Entry) iterator.next(); System.out.print(me2.getKey() + ": "); System.out.println(hmap.get(me2.getKey()).firstName + " "+hmap.get(me2.getKey()).lastName ); > >
1: Ajay Gupta 9: Jayant Verma 6: Mohan Sharma 55: Rahul Dev
Conclusion
This tutorial covered sorting of HashMap according to Value. Sorting for String values differs from Integer values. String values require a comparator for sorting. Whereas, Integer values are directly sorted using Collection.sort().
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us