這裡新建一個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()); } }
userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge)).collect(Collectors.toList());
userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge).reversed()).collect(Collectors.toList());
以上是java使用lambda表達式對List物件集合的某個屬性進行排序的詳細內容。更多資訊請關注PHP中文網其他相關文章!