欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中list里面存放map,根据map中的某一个字段进行排序

程序员文章站 2022-04-15 23:45:35
package com.example.demo;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;/** * *

* Description: *

* * @author xu....
package com.example.demo;

import java.util.ArrayList;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * <p>
 * Description:
 * </p>
 * 
 * @author xuyangwei
 * 
 * @date 2020年7月15日
 * 
 */
public class SortListMap {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		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", "jack");
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("id", "2");
		map2.put("name", "tom");
		Map<String, Object> map3 = new HashMap<String, Object>();
		map3.put("id", "3");
		map3.put("name", "marry");
		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>>() {
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				String id1 = (String) o1.get("id");
				String id2 = (String) o2.get("id"); 
				return id1.compareTo(id2);
			}

		});
		// 排序后
		System.out.println("-------------------");
		for (Map<String, Object> map : list) {
			System.out.println(map.get("id"));
		}

	}

}

 

本文地址:https://blog.csdn.net/q15102780705/article/details/107357450