list集合按某字段排序

2019-08-09  本文已影响0人  平面小狮子

java8 排序方法:


import java.util.ArrayList;

import java.util.Comparator;

import java.util.List;

import java.util.stream.Collectors;

public class TestJava8List {

public static void main(String[] args) {

User user1 = new User(21,"张三");

User user2 = new User(25,"李四");

User user3 = new User(22,"王五");

User user4 = new User(19,"赵柳");

List<User> list = new ArrayList<User>();

list.add(user1);

list.add(user2);

list.add(user3);

list.add(user4);

for(User u :list){

System.out.println(u);

}

List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge))

                .collect(Collectors.toList());

for(User u :newList){

System.out.println(u);

}

}

}

上一篇下一篇

猜你喜欢

热点阅读