java中list裡面存放map,根據map中的某一個欄位進行排序
阿新 • • 發佈:2018-12-29
Java中list裡面存放map,根據map中的某一個欄位進行排序
例如:
- package com;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- publicclass Com {
- /**
- * @param args
- */
-
@SuppressWarnings
- publicstaticvoid 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("id", "1");
- map1.put("name", "p");
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2.put("id", "2");
- map2.put("name", "h");
- Map<String, Object> map3 = new HashMap<String, Object>();
-
map3.put("id"
- map3.put("name", "f");
- list.add(map1);
- list.add(map3);
- list.add(map2);
- //排序前
- for (Map<String, Object> map : list) {
- System.out.println(map.get("id"));
- }
- Collections.sort(list, new Comparator<Map<String, Object>>(){
- publicint compare(Map<String, Object> o1, Map<String, Object> o2) {
- String name1 =(String)o1.get("id");//name1是從你list裡面拿出來的一個
- String name2= (String)o2.get("id"); //name1是從你list裡面拿出來的第二個name
- return name1.compareTo(name2);
- }
- });
- //排序後
- System.out.println("-------------------");
- for (Map<String, Object> map : list) {
- System.out.println(map.get("id"));
- }
- }
- }
1
3
2
- -------------------
2
3