HashMap排序

JAVA

package app.xiaoshouyi.util;

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

public class SortMapByValues {
  public static void main(String[] args) {
    Map 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 aMap) {
    Set> mapEntries = aMap.entrySet();
    System.out.println("Values and Keys before sorting :");
    for (Entry 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> 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 aMap2 = new LinkedHashMap<>();
    for (Entry entry : aList) {
      aMap2.put(entry.getKey(), entry.getValue());
    }
    // printing values after soring of map
    System.out.println("Value " + "-" + "Key");
    for (Entry entry : aMap2.entrySet()) {
      System.out.println(entry.getValue() + "-" + entry.getKey());
    }
  }
}

你可能感兴趣的:(HashMap排序)