amogh kulkarni
amogh kulkarni

Reputation: 53

sort a map from its keys ordered by values from another list

I have a Map with key String and values String and a list of Strings. i want to sort the Map with keys based on the order of values present in the list.

package da.fa;


public class MapSorted {

public static void main(String[] args) {

    List<String> efgh = new ArrayList<String>();
    efgh.add("ccc");
    efgh.add("aaa");
    efgh.add("ddd");
    efgh.add("aaa");

    Map<String, String> abcd = new HashMap<String, String>();
    abcd.put("aaa", "1111");
    abcd.put("bbb", "1111");
    abcd.put("ccc", "1111");
    abcd.put("ddd", "1111");
    abcd.put("eee", "1111");
}
}

in this, abcd should be sorted by the order of what values are in the list efgh has.

Upvotes: 1

Views: 2084

Answers (2)

Anton
Anton

Reputation: 29

If follow suggestion from the aforementioned post how to sort Map values by key in Java, you should write something like this:

Comparator<Foo> comparator = new Comparator<Foo>() {
  List<String> final order = .. //Pass your list here;

  public int compare(String o1, Stringo2) {
    int i1 = order.ingexOf(o1);
    int i2 = order.indexOf(o2);
    return i1 > i2 ? 1 : (i1 < i1 ? -1 : 0);
  }
}
Map<String, String> map = new TreeMap<>(comparator);
map.addAll(abcd);

But what do you need it for? If you want to iterate through this map latter, you can iterate through the list and then fetch value. It will be faster.

And you should remove duplicates from your list:

List<String> efgh = new ArrayList<String>();
...
efgh.add("aaa");
..
efgh.add("aaa");

Otherwise this solution wont work.

Upvotes: 0

chenchuk
chenchuk

Reputation: 5742

HashMaps are non-sortable, use TreeMap instead :

    public static void main(String[] args) {

        // define the needed keys
        List<String> neededKeys = new ArrayList<String>();
        neededKeys.add("ccc");
        neededKeys.add("aaa");
        neededKeys.add("ddd");
        neededKeys.add("aaa");

        // build a simple hashmap (unsorted)
        Map<String, String> unsortedMap = new HashMap<String, String>();
        unsortedMap.put("aaa", "1111");
        unsortedMap.put("bbb", "1111");
        unsortedMap.put("ccc", "1111");
        unsortedMap.put("ddd", "1111");
        unsortedMap.put("eee", "1111");

        // build a sorted TreeMap and pass only the necessary objects
        TreeMap<String, String> sortedMap=new TreeMap<String, String>();
        for(String key:unsortedMap.keySet()){
            // copy needed keys ONLY to a new sorted map
            if (neededKeys.contains(key)){
                sortedMap.put(key, unsortedMap.get(key));
            }
        }

        System.out.println(unsortedMap);
        System.out.println(sortedMap);
    }

Upvotes: 1

Related Questions