Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort the keys of a Map in Java?

Tags:

java

This is a very basic question, I'm just not that good with Java. I have a Map and I want to get a list or something of the keys in sorted order so I can iterate over them.

like image 745
Bialecki Avatar asked Feb 20 '09 21:02

Bialecki


People also ask

How do you sort a map by key value?

Step 1: Create a TreeMap in java with a custom comparator. Step 2: Comparator should compare based on values and then based on the keys. Step 3: Put all key-value pairs from the hashmap into the treemap. Step 4: return the treemap.

Can we sort map based on key?

Using TreeMap (putAll method) The idea is to put all data of HashMap into a TreeMap. The TreeMap follows Red Black Tree based implementation. The map is sorted according to the natural ordering of its keys.

Can you sort HashMap keys?

HashMaps do not store the sorted order of keys by definition. You can however accomplish this by acquiring an array of the keys via: Object[] keys = map. keySet(). toArray(); Then sorting the list with Arrays: Arrays.

How to sort a map in Java?

How to sort a Map in Java 1 Sort by Key#N#1.1 Uses java.util.TreeMap, it will sort the Map by keys automatically.#N#SortByKeyExample1.java#N#package... 2 Sort by Value More ...

How to sort a map by key in Python?

Simple quick to use examples to sort a Map by key, using TreeMap and Stream APIs, in ascending and descending (reverse) orders. By default, all key-value pairs in TreeMap are sorted in their natural order. So all you need to do is add all unsorted key-value pairs in TreeMap.

How to sort a hashmap According to keys in Java?

Sorting a HashMap according to keys in Java. We are given the details of marks scored by students in form of a HashMap, where name of the student is the Key and marks scored is the Value. Our task is to sort the map according to the key values i.e the names of the students in the alphabetical(lexicographical) order.

How to create a new treemap with sorted keys?

If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys. void process (Map<String, Object> original) { Map<String, Object> copy = new TreeMap<String, Object> (original); /* Now use "copy", which will have keys in sorted order. */ ... }


2 Answers

Use a TreeMap, which is an implementation of the SortedMap interface. It presents its keys in sorted order.

Map<String, Object> map = new TreeMap<String, Object>(); /* Add entries to the map in any order. */ ... /* Now, iterate over the map's contents, sorted by key. */ for (Map.Entry<String, ?> entry : map.entrySet()) {   System.out.println(entry.getKey() + ": " + entry.getValue()); } 

If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys.

void process(Map<String, Object> original) {   Map<String, Object> copy = new TreeMap<String, Object>(original);   /* Now use "copy", which will have keys in sorted order. */   ...  } 

A TreeMap works with any type of key that implements the Comparable interface, putting them in their "natural" order. For keys that aren't Comparable, or whose natural ordering isn't what you need, you can implement your own Comparator and specify that in the constructor.

like image 164
erickson Avatar answered Sep 21 '22 02:09

erickson


You have several options. Listed in order of preference:

  1. Use a SortedMap:
    SortedMap<whatever> myNewMap = new TreeMap<whatever>(myOldMap);
    This is vastly preferable if you want to iterate more than once. It keeps the keys sorted so you don't have to sort them before iterating.
  2. There is no #2.
  3. There is no #3, either.
  4. SortedSet<whatever> keys = new TreeSet<whatever>(myMap.keySet());
  5. List<whatever> keys = new ArrayList<whatever>(myMap.keySet()); Collections.sort(keys);

The last two will get you what you want, but should only be used if you only want to iterate once and then forget the whole thing.

like image 44
Michael Myers Avatar answered Sep 21 '22 02:09

Michael Myers