-1

I have a List<Map> myList where each map object has a key, called priority, and I would like to sort this list by the priority. I have no idea, how should I manage it.

Iter Ator
  • 8,226
  • 20
  • 73
  • 164
  • So each map has only one pair of elements? – Boann Sep 26 '14 at 19:17
  • 1
    no. They have more key-value pairs. But each map has a key, called `priority` – Iter Ator Sep 26 '14 at 19:19
  • possible duplicate of [How to sort a List alphabetically using Object name field](http://stackoverflow.com/questions/8432581/how-to-sort-a-listobject-alphabetically-using-object-name-field) – Raedwald Sep 26 '14 at 19:19

3 Answers3

2

each map object has a key, called priority

So i guess, the maps keyset contains Strings. Also, if you want to compare the returned value for the priority key, then this object could implement Comparable.

Collections.sort(myList, new Comparator<Map<String,E extends Comparable>>(){

    @Override
    public int compare(Map<String,E extends Comparable> a, Map<String,E extends Comparable> b){
        return a.get("priority").compareTo(b.get("priority"));
        //alternative:
        //if(a.get("priority").equals(b.get("priority"))return 0;
        //if(a.get("priority") > (b.get("priority"))return 1;
        //return -1;
    }
})
SME_Dev
  • 1,880
  • 13
  • 23
1

public class MyComparator implements Comparator<Map> { public void compare (Map m1, Map m2) { return ((Integer)m1.get("priority")).compareTo(m2.get("priority"))); } } // ... list.sort(new MyComparator());

Replace the Integer cast with another Number subclass if you are not using Integers

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

If using Java8

myList
.stream()
.sorted((obj1, obj2) -> Integer.compare(obj1.get("Priority"), obj2.get("Priority"))
.collect(Collectors.toList())
Sourav 'Abhi' Mitra
  • 2,390
  • 16
  • 15