无法按升序对列表进行排序 [英] Unable to sort the list by ascending order
本文介绍了无法按升序对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Map<String, String> map ;
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
/////OnCreate.............
function1(){
map = new TreeMap<String, String>();
map.put("id", "id");
map.put("amont", "amount");
list.add(map);
System.out.println(list);
}
id = 1,3,5,57,80的输入值
input values for id=1,3,5,57,80
金额的输入值= 100,500,200,10,10000
input values for amount=100,500,200,10,10000
无法按金额的升序对列表进行排序。它仍按插入顺序显示。
Unable to sort the list by ascending order of amount. It still shows in the order it was inserted.
我该如何解决这个问题?我感谢任何帮助。在此先感谢。
How do I fix this? I appreciate any help. Thanks in advance.
预期输出:金额升序:
amt=10 id=4
amt=100 id=1
amt=200 id=3
amt=500 id=2
amt=10000 id=5
推荐答案
假设这是你的输入
Map<String, String> map ;
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
map = new TreeMap<String, String>();
map.put("id","1");
map.put("amount","100");
list.add(map);
map = new TreeMap<String, String>();
map.put("id","2");
map.put("amount","500");
list.add(map);
map = new TreeMap<String, String>();
map.put("id","3");
map.put("amount","200");
list.add(map);
map = new TreeMap<String, String>();
map.put("id","4");
map.put("amount","10");
list.add(map);
map = new TreeMap<String, String>();
map.put("id","5");
map.put("amount","10000");
list.add(map);
这是您的分拣代码
Collections.sort(list, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
String value1 = o1.get("amount");
String value2 = o2.get("amount");
return Integer.parseInt(value1)-Integer.parseInt(value2);
}
});
for (Map<String, String> map1 : list) {
String id = map1.get("id");
String amount = map1.get("amount");
System.out.println("amount= "+amount + " , " +"id = "+id);
}
输出
amount= 10 , id = 4
amount= 100 , id = 1
amount= 200 , id = 3
amount= 500 , id = 2
amount= 10000 , id = 5
更新
替换返回Integer.parseInt(value1)-Integer.parseInt(value2);
如果值为十进制,则代码如下。
Replace return Integer.parseInt(value1)-Integer.parseInt(value2);
with the following code if the values are decimal.
return Double.valueOf(value1).compareTo(Double.valueOf(value2));
这篇关于无法按升序对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文