用Java对HashMap排序
介紹:
在本教程中,我們將學習如何對Java HashMap進行排序。 我們可以按鍵或按值對HashMap進行排序。 我們將討論這兩種策略。
對Java
為了跟上本文的其余部分,我們首先構造一個HashMap:
HashMap<Integer, Student> map = new HashMap<>();map.put(1003, new Student(1003, "Sam")); map.put(1005, new Student(1005, "Joseph")); map.put(1001, new Student(1001, "Kate")); map.put(1002, new Student(1002, "Miranda")); map.put(1004, new Student(1004, "Peter"));其中Student是一個具有ID和名稱作為其字段的POJO:
class Student {private Integer id;private String name;Student(Integer id, String name) {this.id = id;this.name = name;}public String toString() {return "[id="+id + ", name=" + name + "]";}}現在,讓我們看一下可以對HashMap進行排序的不同方法:
1.使用
眾所周知, TreeMap是一個排序的Map ,默認情況下,元素是根據其鍵的自然順序進行排序的。 因此,一種基本方法是將所有元素從HashMap推送到TreeMap:
TreeMap<Integer, Student> sortedMap = new TreeMap<>(map);//Or elseTreeMap<Integer, Student> sortedMap = new TreeMap<>(); sortedMap.putAll(map);請注意, 我們可以將原始HashMap本身傳遞到構造函數中,也可以使用putAll()方法。 這樣,我們的sortedMap將按鍵值的排序順序保存元素:
{1001=[id=1001, name=Kate], 1002=[id=1002, name=Miranda] , 1003=[id=1003, name=Sam], 1004=[id=1004, name=Peter] , 1005=[id=1005, name=Joseph]}2.使用ArrayList:
如果我們只需要排序的鍵或值,而不真正在乎Map ,則可以使用ArrayList。
在這里,我們將首先將鍵或值提取到ArrayList中 ,然后使用Collections.sort()對列表進行排序:
List<Integer> mapKeys = new ArrayList<>(map.keySet()); Collections.sort(mapKeys);//Or List<Student> mapValues = new ArrayList<>(map.values()); Collections.sort(mapValues);在這里,僅當我們的學生實現Comparable時,才可以按值對Map進行排序:
public class Student implements Comparable<Student> {...public int compareTo(Student other) {return this.id.compareTo(other.id);} }之所以如此,是因為我們地圖中的值是一個自定義類型對象– Student 。
3.使用TreeSet:
如果我們還打算避免在鍵或值的結果列表中出現任何重復,則可以選擇TreeSet:
SortedSet<String> mapKeys = new TreeSet<>(map.keySet());同樣,我們可以創建一組排序的地圖值。 但是, 我們必須重寫equals()和hashCode()方法,以使其適用于自定義對象。
4. Java 8流:
從Java 8開始,我們可以使用Stream API對地圖進行排序。 要使用鍵對Java Map進行排序,我們需要:
Map<Integer, Student> sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(e1, e2) -> e1,LinkedHashMap::new));在這里, 我們將排序后的地圖收集到LinkedHashMap中,以保留排序后的order 。
同樣,要按值對地圖進行排序,我們將使用compareByValue() :
sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(e1, e2) -> e1,LinkedHashMap::new));通常,在處理自定義對象時,該對象必須實現Comparable接口。
我們有一篇有關Java 8 Collectors的詳細文章,它將幫助您了解Collectors.toMap()方法的用法。
為了按降序對地圖進行排序,我們可以簡單地使用Collections.reverseOrder():
sortedMapDesc = map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(e1, e2) -> e1,LinkedHashMap::new));讓我們在控制臺上打印sortedMapDesc :
{1005=[id=1005, name=Joseph], 1004=[id=1004, name=Peter], 1003=[id=1003, name=Sam], 1002=[id=1002, name=Miranda],1001=[id=1001, name=Kate]}如我們所見,現在地圖按鍵降序排列。
結論:
在本文中,我們介紹了使用TreeMap,ArrayList或TreeSet對Java HashMap進行排序的各種方法。 我們還介紹了Java 8 Stream API sorted()方法,該方法可以幫助我們按鍵或值對地圖進行排序。
成為第一個發表評論的人。
翻譯自: https://www.javacodegeeks.com/2019/03/sorting-hashmap-java.html
總結
以上是生活随笔為你收集整理的用Java对HashMap排序的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: rest api 可选参数_可选类型AP
- 下一篇: (linux电视系统)
