Damien-Amen
Damien-Amen

Reputation: 7502

Sort hashmap keys for a customized requirement

Say I have a hashmap with keys

{Sean, Michael, John, Alan, Zach}

Now I want to sort these keys as below

{John, Alan, Michael, Zach, Sean}

The names above are just examples. I know we can sort using TreeSort. However it only gives ascending or descending sort. But my requirement above does not have any specific way to sort but it needs to be as mentioned above. How do I achieve that? pls help me.

Upvotes: 0

Views: 62

Answers (2)

Mike Samuel
Mike Samuel

Reputation: 120506

hd1's custom Comparator solution is the typical way to do this. If you just want to preserve a particular ordering though, you can always use a LinkedHashMap and just insert the entries in that order.

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

To produce a map where the entries are in source and the key iteration order is specified by keysInOrder you can do something like:

public static <K, V>
Map<K, V> mapWithKeysInOrder(
    Map<K, V> source, Iterable<? extends K> keysInOrder) {
  Map<K, V> output = new LinkedHashMap<K, V>(source.size());
  for (K key : keysInOrder) {
    output.put(key, source.get(key);
  }
  return output;
}

Upvotes: 3

hd1
hd1

Reputation: 34657

Use a custom Comparator with a java bean wrapper around the String, with, say an Integer?

Upvotes: 3

Related Questions