search

Home  >  Q&A  >  body text

java - list<Map<String, Object>> sorting

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

The obtained chartData is

[{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}]

Now we need to sort her so that the order is TIME1, TIME2... this order, how should we sort it?

漂亮男人漂亮男人2787 days ago734

reply all(2)I'll reply

  • 为情所困

    为情所困2017-05-27 17:43:08

    The problem should be to sort the keys in the Map. You can use Treemap, because the structure of the key is string+int, and it is sorted according to int, so you may need to write a comparator yourself.
    Rough code, the comparator is relatively simple to write, just dismantle it, it may need to be adjusted according to your actual situation

    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);
    

    reply
    0
  • PHP中文网

    PHP中文网2017-05-27 17:43:08

    如非必须要使用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);

    reply
    0
  • Cancelreply