1

I have a list which as elements those are map i want to sort this list over map element value

[{id=45964953, count=1}, {id=46009636, count=1}, {id=45936991, count=1},  {id=45984035, count=2}, {id=45951961, count=1}, {id=45399668, count=31}]

I need to sort it on count value. Can it be done in java

Output should be like this

[ {id=45399668, count=31},{id=45984035, count=2}, {id=45964953, count=1}, {id=46009636, count=1}, {id=45936991, count=1}, {id=45951961, count=1}]
viren
  • 1,073
  • 1
  • 17
  • 41
  • 1
    Come on guys using the search function cannot be that difficult. The same question was asked and answered already today (and in the past). http://stackoverflow.com/questions/28163279/sort-map-by-value-in-java – SubOptimal Jan 27 '15 at 07:09
  • 1
    Smells like homework to me – user12121234 Jan 27 '15 at 07:09
  • possible duplicate of [How to sort a Map on the values in Java?](http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java) – Randyka Yudhistira Jan 27 '15 at 07:11

2 Answers2

1

You can create a class that implements Comparable<Map<String,Integer>> (assuming String and Integer and the key and value of your Map) and compares two Maps based on your criteria.

Then you can pass your list and your Comparator to Collections.sort().

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Java 8 has been out for some time. Impress your teacher with this:

list = list.stream()
    .sorted((m1, m2) -> Integer.compare(m2.get("count"),m1.get("count")))
    .collect(Collectors.toList());

Here's some test code:

List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>() {{
    add(new HashMap<String, Integer>() {{put("id",45964953); put("count", 1);}});
    add(new HashMap<String, Integer>() {{put("id",46009636); put("count", 1);}});
    add(new HashMap<String, Integer>() {{put("id",45936991); put("count", 1);}});
    add(new HashMap<String, Integer>() {{put("id",45984035); put("count", 2);}});
    add(new HashMap<String, Integer>() {{put("id",45951961); put("count", 1);}});
    add(new HashMap<String, Integer>() {{put("id",45399668); put("count", 31);}});
}};                      
list = list.stream().sorted((m1, m2) -> Integer.compare(m2.get("count"), m1.get("count"))).collect(Collectors.toList());
System.out.println(list);

Output:

[{count=31, id=45399668}, {count=2, id=45984035}, {count=1, id=45964953}, {count=1, id=46009636}, {count=1, id=45936991}, {count=1, id=45951961}]
Bohemian
  • 412,405
  • 93
  • 575
  • 722