Java中对list map根据map某个key值进行排序的方法
程序员文章站
2023-12-20 13:08:16
实例如下所示:
package test;
import java.util.arraylist;
import java.util.collecti...
实例如下所示:
package test; import java.util.arraylist; import java.util.collections; import java.util.comparator; import java.util.hashmap; import java.util.list; import java.util.map; public class java_listmapsort { public static void main(string[] args) { // todo auto-generated method stub list<map<string, object>> list = new arraylist<map<string, object>>(); map<string, object> map1 = new hashmap<string, object>(); map1.put("name", "p"); map1.put("cj", "5"); map<string, object> map2 = new hashmap<string, object>(); map2.put("name", "h"); map2.put("cj", "12"); map<string, object> map3 = new hashmap<string, object>(); map3.put("name", "f"); map3.put("cj", "31"); list.add(map1); list.add(map3); list.add(map2); //排序前 for (map<string, object> map : list) { system.out.println(map.get("cj")); } collections.sort(list, new comparator<map<string, object>>() { public int compare(map<string, object> o1, map<string, object> o2) { integer name1 = integer.valueof(o1.get("cj").tostring()) ;//name1是从你list里面拿出来的一个 integer name2 = integer.valueof(o2.get("cj").tostring()) ; //name1是从你list里面拿出来的第二个name return name1.compareto(name2); } }); //排序后 system.out.println("-------------------"); for (map<string, object> map : list) { system.out.println(map.get("cj")); } } }
以上这篇java中对list map根据map某个key值进行排序的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。