HashM-Java面試題:如何對HashMap按索引值排序__Java

來源:互聯網
上載者:User

譯文連結:http://www.codeceo.com/article/java-hashmap-value-sort.html
英文原文:How to Sort HashMap Based On Values in Java
翻譯作者:碼農網 – 小峰

Java中HashMap是一種用於儲存“鍵”和“值”資訊對的資料結構。不同於Array、ArrayList和LinkedLists,它不會維持插入元素的順序。

因此,在鍵或值的基礎上排序HashMap是一個很難的面試問題,如果你不知道如何解決的話。下面讓我們看看如何解決這個問題。

1. HashMap儲存每對鍵和值作為一個Entry<K,V>對象。例如,給出一個HashMap,

 Map<String,Integer> aMap = new HashMap<String,Integer>();

鍵的每次插入,都會有值對應到散列映射上,產生一個Entry <K,V>對象。通過使用這個Entry <K,V>對象,我們可以根據值來排序HashMap。

2.建立一個簡單的HashMap,並插入一些鍵和值。

ap<String,Integer> aMap = new HashMap<String,Integer>();        // adding keys and values        aMap.put("Five", 5);        aMap.put("Seven", 7);        aMap.put("Eight", 8);        aMap.put("One",1);        aMap.put("Two",2);        aMap.put("Three", 3);

3.從HashMap恢複entry集合,如下所示。

Set<Entry<String,Integer>> mapEntries = aMap.entrySet();

4.從上述mapEntries建立LinkedList。我們將排序這個鏈表來解決順序問題。我們之所以要使用鏈表來實現這個目的,是因為在鏈表中插入元素比數組列表更快。

 List<Entry<String,Integer>> aList = new LinkedList<Entry<String,Integer>>(mapEntries);

5.通過傳遞鏈表和自訂比較子來使用Collections.sort()方法排序鏈表。

Collections.sort(aList, new Comparator<Entry<String,Integer>>() {            @Override            public int compare(Entry<String, Integer> ele1,                    Entry<String, Integer> ele2) {                return ele1.getValue().compareTo(ele2.getValue());            }        });

6.使用自訂比較子,基於entry的值(Entry.getValue()),來排序鏈表。

7. ele1.getValue(). compareTo(ele2.getValue())——比較這兩個值,返回0——如果這兩個值完全相同的話;返回1——如果第一個值大於第二個值;返回-1——如果第一個值小於第二個值。

8. Collections.sort()是一個內建方法,僅排序值的列表。它在Collections類中重載。這兩種個方法是

public static <T extends Comparable<? super T>> void sort(List<T> list)public static <T> void sort(List<T> list, Comparator<? super T> c)

9.現在你已經排序鏈表,我們需要儲存鍵和值資訊對到新的映射中。由於HashMap不保持順序,因此我們要使用LinkedHashMap。

// Storing the list into Linked HashMap to preserve the order of insertion.      Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>();        for(Entry<String,Integer> entry: aList) {            aMap2.put(entry.getKey(), entry.getValue());        }

10.完整的代碼如下。

package com.speakingcs.maps;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;public class SortMapByValues {    public static void main(String[] args) {        Map<String,Integer> aMap = new HashMap<String,Integer>();        // adding keys and values        aMap.put("Five", 5);        aMap.put("Seven", 7);        aMap.put("Eight", 8);        aMap.put("One",1);        aMap.put("Two",2);        aMap.put("Three", 3);        sortMapByValues(aMap);    }    private static void sortMapByValues(Map<String, Integer> aMap) {        Set<Entry<String,Integer>> mapEntries = aMap.entrySet();        System.out.println("Values and Keys before sorting ");        for(Entry<String,Integer> entry : mapEntries) {            System.out.println(entry.getValue() + " - "+ entry.getKey());        }        // used linked list to sort, because insertion of elements in linked list is faster than an array list.         List<Entry<String,Integer>> aList = new LinkedList<Entry<String,Integer>>(mapEntries);        // sorting the List        Collections.sort(aList, new Comparator<Entry<String,Integer>>() {            @Override            public int compare(Entry<String, Integer> ele1,                    Entry<String, Integer> ele2) {                return ele1.getValue().compareTo(ele2.getValue());            }        });        // Storing the list into Linked HashMap to preserve the order of insertion.         Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>();        for(Entry<String,Integer> entry: aList) {            aMap2.put(entry.getKey(), entry.getValue());        }        // printing values after soring of map        System.out.println("Value " + " - " + "Key");        for(Entry<String,Integer> entry : aMap2.entrySet()) {            System.out.println(entry.getValue() + " - " + entry.getKey());        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.