java - 按字母顺序对从服务器获取的响应进行排序

标签 java android json retrofit2

我从服务器得到这样的响应,

[  
 {  
  "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());
 }
};

关于java - 按字母顺序对从服务器获取的响应进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42795998/

相关文章:

java - 在 Java 中,我应该在 foreach 之前在本地复制一个 volatile 引用吗?

java - Spring集成DSL : PublishSubscribeChannel order

java - JSF 不工作 : Select SelectOneMenu And Dynamically Update Other SelectOneMenu With Ajax

python - 解析没有索引的Json

javascript - Monaco Editor 不会显示在 react 应用程序中

java - 我可以在 Apache Camel 中拥有多个回复者吗

Android:如何检查文件是否为图像?

java - 安卓,org.w3c.dom : No validating DocumentBuilder implementation available

android - 如何在后台检测数据库新更新并通知用户

c# - 如何使用 Linq 检查 JSON 中的标签