开发者

How to sort Map<Integer, MyClass> by a property of MyClass?

开发者 https://www.devze.com 2023-04-10 17:20 出处:网络
I am using GSON to deserialize JSON like this: Type mapType = new TypeToken<Map<Integer, MyClass> >() {}.getType(); // define generic type

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 MyClas开发者_StackOverflow社区s{
    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.

0

精彩评论

暂无评论...
验证码 换一张
取 消