Gson sort ArrayList of TreeMap by value

Jasonca1 :

I have a ArrayList of LinkedTreeMap objects in Java from the Gson library. There is a key on each object, lets say the key is labeled "code" and each value is a string. I am wanting to sort the overall ArrayList of these LinkedTreeMap objects by that particular key (the "code" key) in ascending order (but also curious how one could do it in reverse order as well). I understand you would have to implement the Comparable interface to get this to work, I'm just not sure how to go about doing it.

dpr :

Implementing the Comparable interface might be too much overhead in your example (you would have to introduce a dedicated class for your LinkedTreeMap that implements Comparable) additionally implementing only makes sense, if your class has a natural order, that is always used to sort elements of this class.

Implementing a Comparator is much more flexible and pretty easy to do. This class can then be used to sort your list:

public static void main(String[] args) {
  List<Map<String, String>> list = new ArrayList<>(); // get your list from somewhere
  list.sort(new MapComparator());
}

private static class MapComparator implements Comparator<Map<String, String>> {
  @Override
  public int compare(Map<String, String> o1, Map<String, String> o2) {
    // probably do some error handling here to handle cases where "code" is not present in the map
    return o1.get("code").compareTo(o2.get("code")); 
  }
} 

By using new MapComparator().reversed() you can simply reverse the order of your comparator.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=393590&siteId=1