How to sort a HashMap in Java [duplicate]

Do you have to use a HashMap? If you only need the Map Interface use a TreeMap


If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:

Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);

people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);

// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());

Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));

for (Person p : peopleByAge) {
    System.out.println(p.getName() + "\t" + p.getAge());
}

If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>, though the semantics of sets and lists are a bit different.


Sorted List by hasmap keys:

SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet());

Sorted List by hashmap values:

SortedSet<String> values = new TreeSet<String>(myHashMap.values());

In case of duplicated map values:

List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);

Good Luck!


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.


Seems like you might want a treemap.

http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

You can pass in a custom comparator to it if that applies.