我正在从服务器收到这样的响应,

[
 {
  "id":"b2",
  "type":"ball"
 },
 {
  "id":"a1",
  "type":"apple",
 },
 {
  "id":"d4",
  "type":"dog",
 },
 {
  "id":"c3",
  "type":"cat",
 }
]


但我需要根据字母和类型对上述响应数据进行排序。然后显示列表,我正在使用模型来解析数据。

最佳答案

您将JSON解析为什么数据结构?例如,如果您有一个类似于以下内容的Item类:

class Item {
  Item(String id, String type) { ... }
  String getType() { ... }
  String getId() { ... }
}


然后,您将该JSON解析为某种List<Item>,则以下内容应适用于按类型(API级别24+)进行排序,请参见Comparator.comparing

List<Item> items = ...; // however you parse the JSON
Comparator<Item> byType = Comparator.comparing(Item::getType);
Collection.sort(items, byType); // items will now be sorted


对于适用于较旧API级别的更通用的方法,可以定义byType比较器,如下所示:

Comparator<Item> byType = new Comparator<Item> {
 public int compare(Item a, Item b) {
   return a.getType().compareTo(b.getType());
 }
};

09-10 06:56
查看更多