How to sort a HashMap in Java

2018-12-31 19:04发布

How are we able to sort a HashMap<key, ArrayList>?

I want to sort on the basis of a value in the ArrayList.

17条回答
永恒的永恒
2楼-- · 2018-12-31 19:18

A proper answer.

HashMap<Integer, Object> map = new HashMap<Integer, Object>();

ArrayList<Integer> sortedKeys = new ArrayList<Integer>(map.keySet());
Collections.sort(sortedKeys, new Comparator<Integer>() {
  @Override
  public int compare(Integer a, Integer b) {
    return a.compareTo(b);
  }
});

for (Integer key: sortedKeys) {
  //map.get(key);
}

Note that HashMap itself cannot maintain sorting, as other answers have pointed out. It's a hash map, and hashed values are unsorted. You can thus either sort the keys when you need to and then access the values in order, as I demonstrated above, or you can find a different collection to store your data, like an ArrayList of Pairs/Tuples, such as the Pair found in Apache Commons:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

查看更多
荒废的爱情
3楼-- · 2018-12-31 19:21

In Java 8:

Comparator<Entry<String, Item>> valueComparator = 
    (e1, e2) -> e1.getValue().getField().compareTo(e2.getValue().getField());

Map<String, Item> sortedMap = 
    unsortedMap.entrySet().stream().
    sorted(valueComparator).
    collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                             (e1, e2) -> e1, LinkedHashMap::new));

Using Guava:

Map<String, Item> map = ...;
Function<Item, Integer> getField = new Function<Item, Integer>() {
    public Integer apply(Item item) {
        return item.getField(); // the field to sort on
    }
};
comparatorFunction = Functions.compose(getField, Functions.forMap(map));
comparator = Ordering.natural().onResultOf(comparatorFunction);
Map<String, Item> sortedMap = ImmutableSortedMap.copyOf(map, comparator);
查看更多
倾城一夜雪
4楼-- · 2018-12-31 19:21

I have developed a class which can be used to sort a map on the basis of keys and values. The basic idea is if you have sort a map using keys then create a TreepMap from your Map which will sort the map by keys. And in case of sorting by values create a list from entrySet and sort the list using comparator interface.

Here is the full solution :

public static void main(String[] args) {
    Map<String, Integer> unSortedMap = new LinkedHashMap<String, Integer>();
    unSortedMap.put("A", 2);
    unSortedMap.put("V", 1);
    unSortedMap.put("G", 5);
    System.out.println("Unsorted Map :\n");
    for (Map.Entry<String, Integer> entry : unSortedMap.entrySet()) {
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
    System.out.println("\n");
    System.out.println("Sorting Map Based on Keys :\n");
    Map<String, Integer> keySortedMap = new TreeMap<String, Integer>(unSortedMap);
    for (Map.Entry<String, Integer> entry : keySortedMap.entrySet()) {
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
    System.out.println("\n");
    System.out.println("Sorting Map Based on Values :\n");
    List<Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(unSortedMap.entrySet());
    Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {

        @Override
        public int compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2) {
            return obj1.getValue().compareTo(obj2.getValue());
        }
    });
    unSortedMap.clear();
    for (Entry<String, Integer> entry : entryList) {
        unSortedMap.put(entry.getKey(), entry.getValue());
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
}

Code is properly tested :D

查看更多
人间绝色
5楼-- · 2018-12-31 19:24

Convert hashmap to a ArrayList with a pair class

Hashmap<Object,Object> items = new HashMap<>();

to

List<Pair<Object,Object>> items = new ArrayList<>();

so you can sort it as you want, or list sorted by adding order.

查看更多
不流泪的眼
6楼-- · 2018-12-31 19:24

Sorting HashMap by value in Java:

public class HashMapSortByValue {
    public static void main(String[] args) {

        HashMap<Long,String> unsortMap = new HashMap<Long,String>();
            unsortMap.put(5l,"B");
            unsortMap.put(8l,"A");
            unsortMap.put(2l, "D");
            unsortMap.put(7l,"C" );

            System.out.println("Before sorting......");
            System.out.println(unsortMap);

            HashMap<Long,String> sortedMapAsc = sortByComparator(unsortMap);
            System.out.println("After sorting......");
            System.out.println(sortedMapAsc);

    }

    public static HashMap<Long,String> sortByComparator(
            HashMap<Long,String> unsortMap) {

            List<Map.Entry<Long,String>> list = new LinkedList<Map.Entry<Long,String>>(
                unsortMap.entrySet());

            Collections.sort(list, new Comparator<Map.Entry<Long,String>> () {
                public int compare(Map.Entry<Long,String> o1, Map.Entry<Long,String> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            });

            HashMap<Long,String> sortedMap = new LinkedHashMap<Long,String>();
            for (Entry<Long,String> entry : list) {
              sortedMap.put(entry.getKey(), entry.getValue());
            }
            return sortedMap;
          }

}
查看更多
临风纵饮
7楼-- · 2018-12-31 19:25

http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/

get the keys

List keys = new ArrayList(yourMap.keySet());

Sort them

 Collections.sort(keys)

print them.

In any case, you can't have sorted values in HashMap (according to API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time ].

Though you can push all these values to LinkedHashMap, for later use as well.

查看更多
登录 后发表回答