考慮一類User
如何在列表中找到最大日期<Object>?
public class User{
int userId;
String name;
Date date;
}
現在我有大小20的List<User>
,我怎麼能找到最大日在列表中不使用人工迭代器?
考慮一類User
如何在列表中找到最大日期<Object>?
public class User{
int userId;
String name;
Date date;
}
現在我有大小20的List<User>
,我怎麼能找到最大日在列表中不使用人工迭代器?
因爲你所要求的lambda表達式,你可以使用下面的語法與Java 8:
Date maxDate = list.stream().map(u -> u.date).max(Date::compareTo).get();
,或者,如果你有日期的吸:
Date maxDate = list.stream().map(User::getDate).max(Date::compareTo).get();
謝謝,我也爲我做了這個工作!這個解決方案避免使用'比較器',它可能很煩人,因爲它不能識別'流'中的對象類型。 – bashoogzaad
你需要先使用map才能獲得日期流 –
這是一個更安全的方式來使用orElse(null)然後.get(); – zeroke
class User implements Comparable<User> {
int UserId;
String name;
Date date;
//all your getter and setters go here
public int compareTo(User usr1) {
return this.getDate().compareTo(usr1.getDate());
}
}
然後使用
Collections.sort(YourUserList);
Comparator<User> cmp = new Comparator<User>() {
@Override
public int compare(User user1, User user2) {
return user1.date.compareTo(user2.date);
}
};
Collections.max(list, cmp);
你的問題對我來說還不清楚。你能詳細解釋一下嗎? – Maroun
使用自定義比較器對您的列表進行排序並獲取第一個結果。 –
你是什麼意思的「手動迭代器」。 'Collections.max(yourList,yourComparator)'算作「手動」嗎? – Pshemo