工作中,有时会需要对集合内的元素进行排序。利用java8,可以很方便的对List内的元素进行正序、倒叙操作~
-
对数字排序
//对数字进行排序Listnums = Arrays.asList(3,1,5,2,9,8,4,10,6,7);nums.sort(Comparator.reverseOrder()); //reverseOrder倒序System.err.println("倒序:"+nums);//倒序:[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]nums.sort(Comparator.naturalOrder());//naturalOrder自然排序即:正序System.err.println("正序:"+nums);//正序:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
-
按照对象某个属性进行排序
//按照对象某个属性进行排序:例如年龄Listusers = new ArrayList<>();users.add(new User("u1",22));users.add(new User("u2",18));users.add(new User("u3",35));users.add(new User("u4",16));users.add(new User("u5",40));/** * o1,o2表示需要比较的对象, * 正序:o1.getAge().compareTo(o2.getAge()) * 倒序:o2.getAge().compareTo(o1.getAge()) **/users.sort((o1, o2) -> o1.getAge().compareTo(o2.getAge()));System.err.println("age正序:"+users);//age正序:[User{name='u4', age=16}, User{name='u2', age=18}, User{name='u1', age=22}, User{name='u3', age=35}, User{name='u5', age=40}]users.sort((o1, o2) -> o2.getAge().compareTo(o1.getAge()));System.err.println("age倒序:"+users);//age倒序:[User{name='u5', age=40}, User{name='u3', age=35}, User{name='u1', age=22}, User{name='u2', age=18}, User{name='u4', age=16}]