1

I am using GSON to deserialize JSON like this:

Type mapType = new TypeToken<Map<Integer, MyClass> >() {}.getType(); // define generic type
Map<Integer, MyClass> jsData= gson.fromJson(r, mapType);

MyClass is:

public class MyClass{
    private String status;  
    private String mObjectType; //Where mObjectType = Type1 = Type2 = Type3 = Type4
    //some more value + getters/setters
}

JSON response is:

{
  128: {
    status: someValue,
    mObjectType: Type1
  },
  124: {
    status: someValue,
    mObjectType: Type3
  },
  123: {
    status: someValue,
    mObjectType: Type2
  }
}

Thereafter I have Map with JSON data and I can iterate through Map. I want sort this Map by value mObjectType for insert into ListAdepter in a certain order, there ObjectType will be header each section.

How can I sort this map on mObjectType? Through iterator I can get all of values for current key. Or will it be better implement a custom Comparator?

upd

I did it like:

Iterator i = jsData.entrySet().iterator();
    while (i.hasNext()){
        Map.Entry iLookObj = (Map.Entry)i.next();
        MyClass temp = (MyClass)iWatchObj.getValue();
        if(temp.getObjectType().equals("ObjectType1")){
            ObjectType1.add(temp);
        } else if (temp.getObjectType().equals("ObjectType2")){
            ObjectType2.add(temp);
        }else if (temp.getObjectType().equals("ObjectType3")){
            ObjectType3.add(temp);
        }   
    }

Do not know yet how differently do it.

Mrusful
  • 1,503
  • 1
  • 18
  • 32
  • 2
    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) – BalusC Oct 05 '11 at 17:13
  • Double is simple. If i will compare MyClass objects, i don think what they sorted how i want. I did it like in update. – Mrusful Oct 06 '11 at 14:40
  • 1
    Just compare on the desired `MyClass`' property? Cast both `Object`s inside `compare()` to `MyClass`, get the desired property and compare on it. – BalusC Oct 06 '11 at 14:55
  • I have a problem with the optimal code, but what's the difference in speed will be? Only in memory allocation, i'm wrong? Good advice would be great. Thanks a lot. – Mrusful Oct 06 '11 at 22:14

0 Answers0