这里新建一个UserInfo对象,用来测试lambda表达式排序,属性如下:
public class UserInfo { private int id; private int age; private String name; public UserInfo(int id, int age, String name) { this.id = id; this.age = age; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; }测试 public void setName(String name) { this.name = name; }
相关视频教程推荐:java学习
开始造数据,测试下按照年龄大小正序排序:
public static void main(String[] args) { UserInfo user1 = new UserInfo(1, 20, "赵"); UserInfo user2 = new UserInfo(2, 25, "钱"); UserInfo user3 = new UserInfo(3, 23, "孙"); UserInfo user4 = new UserInfo(7, 16, "李"); UserInfo user5 = new UserInfo(6, 19, "周"); UserInfo user6 = new UserInfo(5, 12, "吴"); List<UserInfo> userInfoList = new ArrayList<>(); userInfoList.add(user2); userInfoList.add(user1); userInfoList.add(user3); userInfoList.add(user4); userInfoList.add(user5); userInfoList.add(user6); //使用lambda表达式对age大小正序排序 userInfoList = userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge)) .collect(Collectors.toList()); for (UserInfo userInfo : userInfoList) { System.out.println(userInfo.toString()); } }
输出结果如下:
测试按照年龄大小倒序排序:
public static void main(String[] args) { UserInfo user1 = new UserInfo(1, 20, "赵"); UserInfo user2 = new UserInfo(2, 25, "钱"); UserInfo user3 = new UserInfo(3, 23, "孙"); UserInfo user4 = new UserInfo(7, 16, "李"); UserInfo user5 = new UserInfo(6, 19, "周"); UserInfo user6 = new UserInfo(5, 12, "吴"); List<UserInfo> userInfoList = new ArrayList<>(); userInfoList.add(user2); userInfoList.add(user1); userInfoList.add(user3); userInfoList.add(user4); userInfoList.add(user5); userInfoList.add(user6); //使用lambda表达式对age大小倒序排序,发现就是多加了个reversed()方法 userInfoList = userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge). reversed()).collect(Collectors.toList()); for (UserInfo userInfo : userInfoList) { System.out.println(userInfo.toString()); } }
输出结果如下:
总结下排序使用方法:
1、按照某个字段正序排序:
userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge)).collect(Collectors.toList());
2、按照某个字段倒序排序:
userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge).reversed()).collect(Collectors.toList());
以上各种参数根据自己业务对号入座即可。
相关文章教程推荐:java入门学习
以上就是java使用lambda表达式对List对象集合的某个属性进行排序的详细内容,
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)