您的位置:首页技术文章
文章详情页

java - list<Map<String, Object>> 排序

【字号: 日期:2023-11-17 09:54:03浏览:45作者:猪猪

问题描述

利用List<java.util.Map<String,Object>> charData = (List<java.util.Map<String, Object>>) map.get('data');

得到的chartData 为

[{TIME21=0, TIME22=2, TIME23=0, TIME12=0, TIME13=1, TIME10=0, TIME20=0, TIME11=1, TIME17=0, TIME9=2, TIME16=0, TIME15=0, TIME14=1, TIME5=0, TIME6=0, TIME19=0, TIME7=0, TIME18=1, TIME8=4, TIME1=0, TIME2=0, TIME3=0, TIME4=0, TIME0=0}]

现在要对她进行排序,使其的顺序为TIME1,TIME2.....这样的顺序 ,应该怎么排序呢?

问题解答

回答1:

看问题应该是对Map里面的key进行排序,可以使用Treemap,因为看key的结构是string+int,根据int排序,所以可能需要自己写个比较器。大致的代码,比较器写的比较简单,就是拆了一下,可能需要根据你的实际情况调整

TreeMap<String,Object> treemap = new TreeMap<String,Object>( new Comparator<String>() { @Override public int compare(String o1, String o2) { Integer i1 = Integer.parseInt(o1.substring(4)); Integer i2 = Integer.parseInt(o2.substring(4)); return i1.compareTo(i2); } });treemap.put('TIME21',0);treemap.put('TIME11',0);treemap.put('TIME1',0);treemap.put('TIME2',0);回答2:

如非必须要使用Map,建议使用对象代替Map

List<Map<String, Object>> list = new ArrayList<>();Map<String, Object> map1 = new HashMap<>();Map<String, Object> map2 = new HashMap<>();Map<String, Object> map3 = new HashMap<>();map1.put('TIME1', 1);map2.put('TIME13', 2);map3.put('TIME15', 3);list.add(map3);list.add(map2);list.add(map1);System.out.println(list);list.sort(new Comparator<Map<String, Object>>() { @Override public int compare(Map<String, Object> o1, Map<String, Object> o2) {String s1 = '';for (String s : o1.keySet()) { s1 = s;}String s2 = '';for (String s : o2.keySet()) { s2 = s;}//获取TIME字符串后面的数字Integer i1 = Integer.parseInt(s1.substring(4));Integer i2 = Integer.parseInt(s2.substring(4));return i1.compareTo(i2); }});System.out.println('--------------');System.out.println(list);

标签: java