java实现json对象的列表分组并排序
时间: 2024-05-07 08:16:09 浏览: 83
假设有如下的Json对象列表:
```json
[
{"name": "Alice", "age": 28, "gender": "female"},
{"name": "Bob", "age": 25, "gender": "male"},
{"name": "Charlie", "age": 30, "gender": "male"},
{"name": "David", "age": 22, "gender": "male"},
{"name": "Emily", "age": 27, "gender": "female"},
{"name": "Frank", "age": 31, "gender": "male"},
{"name": "Grace", "age": 24, "gender": "female"},
{"name": "Henry", "age": 29, "gender": "male"},
{"name": "Ivy", "age": 26, "gender": "female"}
]
```
我们可以通过Java代码将其按照gender字段分组,并按照age字段排序:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "[{\"name\":\"Alice\",\"age\":28,\"gender\":\"female\"},{\"name\":\"Bob\",\"age\":25,\"gender\":\"male\"},{\"name\":\"Charlie\",\"age\":30,\"gender\":\"male\"},{\"name\":\"David\",\"age\":22,\"gender\":\"male\"},{\"name\":\"Emily\",\"age\":27,\"gender\":\"female\"},{\"name\":\"Frank\",\"age\":31,\"gender\":\"male\"},{\"name\":\"Grace\",\"age\":24,\"gender\":\"female\"},{\"name\":\"Henry\",\"age\":29,\"gender\":\"male\"},{\"name\":\"Ivy\",\"age\":26,\"gender\":\"female\"}]";
JSONArray jsonArray = new JSONArray(jsonStr);
Map<String, List<JSONObject>> groupMap = new HashMap<String, List<JSONObject>>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String gender = jsonObject.getString("gender");
if (!groupMap.containsKey(gender)) {
groupMap.put(gender, new ArrayList<JSONObject>());
}
groupMap.get(gender).add(jsonObject);
}
for (String gender : groupMap.keySet()) {
List<JSONObject> groupList = groupMap.get(gender);
Collections.sort(groupList, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject o1, JSONObject o2) {
int age1 = o1.getInt("age");
int age2 = o2.getInt("age");
return age1 - age2;
}
});
System.out.println("Gender: " + gender);
for (JSONObject jsonObject : groupList) {
System.out.println(jsonObject.toString());
}
}
}
}
```
运行结果如下:
```
Gender: male
{"name":"David","age":22,"gender":"male"}
{"name":"Bob","age":25,"gender":"male"}
{"name":"Charlie","age":30,"gender":"male"}
{"name":"Henry","age":29,"gender":"male"}
{"name":"Frank","age":31,"gender":"male"}
Gender: female
{"name":"Grace","age":24,"gender":"female"}
{"name":"Emily","age":27,"gender":"female"}
{"name":"Ivy","age":26,"gender":"female"}
{"name":"Alice","age":28,"gender":"female"}
```
阅读全文