Ste*_*mau 0 java sorting arraylist
我正在获取json数据:
[
{
"name": "A",
"count": "2"
},
{
"name": "B",
"count": "1"
},
{
"name": "A",
"count": "3"
},
{
"name": "C",
"count": "10"
},
{
"name": "B",
"count": "2"
}
]
Run Code Online (Sandbox Code Playgroud)
所以我使用for循环,正常的东西迭代数据.但我想最终得到arraylist这样的结论:
Ç - > 7
A - > 5
乙 - > 3
请注意,list从最高到最低排序.到目前为止我尝试的是:
//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
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我应该使用,Comparator.sort()但我不知道如何到达list那里,因为我把名称和数量混合在一起,如:C-->7
我一直在强调逻辑应该是什么样的,对此有何帮助?
你的"心理"模型错了.
如果你的对象有一个名字和一个计数,那么就不要把它们推入像
"name-->count"
Run Code Online (Sandbox Code Playgroud)
相反:创建自己的包含这些属性的自定义类.然后你就可以创建一个(不知)简单的比较是一流的.如果您打算在某些时候执行此操作,这也简化了写回JSON数据的过程.
如果你坚持继续你的破碎方法,那么你必须创建一个知道如何对这种类型的字符串进行排序的比较器.换句话说:你的比较器必须拆分这样的"n - > c"字符串; 并从中推断出名称和数量; 然后做好自己的工作.但正如所说; 你最好放弃这个想法.
严肃地说:这是一个非常糟糕的做法.Java是一种强类型语言; 并且将多个值编码为一个扁平字符串,您将完全放弃Java类型系统为您提供的"帮助".
| 归档时间: |
|
| 查看次数: |
415 次 |
| 最近记录: |