我得到的 json
数据如下:
[
{
"name": "A",
"count": "2"
},
{
"name": "B",
"count": "1"
},
{
"name": "A",
"count": "3"
},
{
"name": "C",
"count": "10"
},
{
"name": "B",
"count": "2"
}
]
所以我使用 for
循环迭代数据,正常的东西。但我想最终得到一个像这样的arraylist
:
C-->7
A-->5
B-->3
请注意,列表
按从最高到最低的顺序排列。
到目前为止我尝试过的是:
//create my arraylists
//has both name and count
ArrayList<String>namesWithCountList = new ArrayList<>();
//has only names
ArrayList<String>namesList = new ArrayList<>();
//get json array..
//iterate using for loop
for (int i = 0; i < myJsonArray.length(); i++) {
String nameStr = jsonObj.getString("name");
int count = jsonObj.getInt("count");
index = namesList.indexOf(name);//get index of the name
if (index < 0) {
// name doesnt exist in namesList, so we add it
namesList.add(nameStr);
namesWithCountList.add(nameStr+"-->"+count);
}else{
//name exists so we only add the count to existing list
}
}
我知道我应该使用Comparator.sort()
,但我不知道如何在那里获取我的list
,因为我将名称和计数混合在一起,例如:C-->7
我一直在强调逻辑应该是什么样子,对此有什么帮助吗?
最佳答案
你的“心理”模型是错误的。
如果您的对象有名称和计数,那么只需不要将它们插入像
这样的字符串中"name-->count"
相反:创建您自己的自定义类来保存这些属性。然后您可以为该类创建一个(以某种方式)更简单的比较器。如果您打算在某个时候写回 JSON 数据,这也简化了写回 JSON 数据的过程。
如果您坚持继续使用损坏的方法,那么您必须创建一个知道如何对此类字符串进行排序的比较器。换句话说:你的比较器必须分割这样的“n-->c”字符串;并从中推断出名称和计数;然后完成它的工作。但正如所说;你最好放弃这个想法。
严肃地说:这是一种非常糟糕的做法。 Java 是一种强类型语言;将多个值编码到一个平面字符串中,您完全放弃了Java类型系统为您提供的“帮助”。
关于java - 如何按降序对包含字符串的 arrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41609445/