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}]