list集合按元素的某一属性排序

原创 健旺  2018-05-24 10:11  阅读 2,767 次
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: Sort 
 * @Description: list集合按元素的某一属性排序
 * @author ljw
 * @date 2018年5月24日
 */
public class Sort {
	
	public static void main(String[] args) {
		
		List<Map<String, Integer>> list = new ArrayList<>();
		
		for (int i = 0; i < 10; i++) {
			Map<String, Integer> map = new HashMap<>();
			Integer random = (int)(Math.random() * 100);
			map.put("random", random);
			list.add(map);
		}
		
		//排序前
		System.out.println("排序前:" + list);
		
		Collections.sort(list, new Comparator<Map<String, Integer>>() {
            public int compare(Map<String, Integer> m1, Map<String, Integer> m2) {
            	//降序
            	//return m2.get("random").compareTo(m1.get("random"));
            	//升序
            	return m1.get("random").compareTo(m2.get("random"));            	
            }
        });
		
		//排序后
		System.out.println("排序后:" + list);
	}
}

 
排序前:[{random=79}, {random=44}, {random=38}, {random=65}, {random=43}, {random=83}, {random=90}, {random=87}, {random=83}, {random=13}]
 
排序后:[{random=13}, {random=38}, {random=43}, {random=44}, {random=65}, {random=79}, {random=83}, {random=83}, {random=87}, {random=90}]

本文地址:http://www.256it.com/134.html
版权声明:本文为原创文章,版权归 健旺 所有,欢迎分享本文,转载请保留出处!

发表评论


表情