美文网首页
HashMap排序

HashMap排序

作者: SummerC0ld | 来源:发表于2017-04-06 15:44 被阅读0次

JAVA

package app.xiaoshouyi.util;

import java.util.*;
import java.util.Map.Entry;

public class SortMapByValues {
  public static void main(String[] args) {
    Map<String, Integer> aMap = new HashMap<>();
// 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<>(mapEntries);
    // sorting the List
    aList.sort(Comparator.comparing(Entry::getValue));
    // Storing the list into Linked HashMap to preserve the order of insertion.
    Map<String, Integer> aMap2 = new LinkedHashMap<>();
    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());
    }
  }
}

相关文章

网友评论

      本文标题:HashMap排序

      本文链接:https://www.haomeiwen.com/subject/mrdqattx.html