码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA中对list map根据map某个key值进行排序

时间:2017-11-07 22:10:11      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:array   排序   compareto   stat   一个   tostring   span   log   string   

 

 

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("age", "5");
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("name", "h");
        map2.put("age", "12");
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("name", "f");
        map3.put("age", "31");
        list.add(map1);
        list.add(map3);
        list.add(map2);
        //排序前 
        for (Map<String, Object> map : list) {
            System.out.println(map.get("age"));
        }
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer age1= Integer.valueOf(o1.get("age").toString()) ;//age1是从你list里面拿出来的第一个 age
                Integer age2= Integer.valueOf(o2.get("age").toString()) ; //age1是从你list里面拿出来的第二个age
                return age1.compareTo(age2);   //return age2.compareTo(age1);为降序
            }
        });
        //排序后 
        System.out.println("-------------------");
        for (Map<String, Object> map : list) {
            System.out.println(map.get("age"));
        }
    }
}

 

JAVA中对list map根据map某个key值进行排序

标签:array   排序   compareto   stat   一个   tostring   span   log   string   

原文地址:http://www.cnblogs.com/Dreamice/p/7800905.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!