[{TIME21=0, TIME22=2, TIME23=0, TIME12=0, TIME13=1, LOAN_AMT=500, TIME10=0, TIME20=0, TIME11=1, TIME17=0, TIME9=2, TIME16=0, TIME15=0, TIME14=1, TIME5=0, REG_DT=20170517, TIME6=0, TIME19=0, TIME7=0, TIME18=1, TIME8=4, TIME1=0, TIME2=0, TIME3=0, TIME4=0, TIME0=0}, {TIME21=3, TIME22=2, TIME23=3, TIME12=6, TIME13=7, LOAN_AMT=1000, TIME10=8, TIME20=2, TIME11=6, TIME17=6, TIME9=7, TIME16=2, TIME15=7, TIME14=5, TIME5=0, REG_DT=20170517, TIME6=1, TIME19=1, TIME7=3, TIME18=1, TIME8=5, TIME1=0, TIME2=1, TIME3=0, TIME4=0, TIME0=3}]
这是一个列表,表单是List>,我想对它进行排序让它显示像TIME1,TIME2 ......,我应该怎么做,而这样的TIME1类型是BigDecimal ,这是我的代码,但它不起作用
for (Map<String, Object> dataMap : chartData) {
List<Object> objs = new ArrayList<Object>();
for (final Map.Entry<String, Object> entry : dataMap.entrySet()) {
Collections.sort(chartData,new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
BigDecimal s1 = (BigDecimal) o1.get(entry.getKey());
BigDecimal s2 = (BigDecimal) o2.get(entry.getKey());
int result = s1.compareTo(s2);
if (result < 0) {
System.out.println("a < b");
return 1;
}else {
System.out.println("a>b");
return -1;
}
}
});
}
}
答案 0 :(得分:1)
要按键对Map进行排序,您必须将地图的条目包装到支持LinkedList
等排序的集合中。这是一个例子:
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByKey( Map<K, V> map )
{
List<Map.Entry<K, V>> list =
new LinkedList<>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return ( o1.getKey() ).compareTo( o2.getKey() );
}
} );
}
如您所见List<Map.Entry<K, V>> list
包含地图的条目。要将已排序的列表转换为已排序的地图,请使用LinkedHashMap
:
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list)
{
result.put( entry.getKey(), entry.getValue() );
}
return result;