考虑一个班级User
public class User{
int userId;
String name;
Date date;
}
现在我有一个大小为20的List<User>
,如何在不使用手动迭代器的情况下在列表中找到最大日期?
答案 0 :(得分:87)
由于您要求使用lambdas,因此可以在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();
答案 1 :(得分:4)
Comparator<User> cmp = new Comparator<User>() {
@Override
public int compare(User user1, User user2) {
return user1.date.compareTo(user2.date);
}
};
Collections.max(list, cmp);
答案 2 :(得分:4)
接受答案的一个小改进是进行空检查并获得完整的对象。
public class DateComparator {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
employees.add(new Employee(4, "name4", null));
employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
System.out.println(employees);
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
System.out.println(format.format(maxDate));
//Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
System.out.println(" minDatedEmployee : " + minDatedEmployee);
}
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); // minus number would decrement the days
return cal.getTime();
}
}
你会得到以下结果:
[Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]
minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]
更新:如果列表本身为空怎么办?
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
System.out.println(format.format(maxDate));
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
答案 3 :(得分:3)
只需使用Kotlin!
val list = listOf(user1, user2, user3)
val maxDate = list.maxBy { it.date }?.date
答案 4 :(得分:1)
LocalDate maxDate = dates.stream()
.max( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
LocalDate minDate = dates.stream()
.min( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
答案 5 :(得分:0)
您不应直接调用.get()。 Stream::max
返回的Optional <>旨在从.orElse ...内联处理中受益。
如果您确定参数的大小为20:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElseThrow(() -> new IllegalArgumentException("Expected a list of size: 20. Was: 0"));
如果支持空列表,则返回一些默认值,例如:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElse(new Date(Long.MIN_VALUE));
从接受的答案中抄录至:@ JimmyGeers,@ assylias。
答案 6 :(得分:0)
import static java.util.Comparator.naturalOrder;
...
list.stream()
.map(User::getDate)
.max(naturalOrder())
.orElse(null) // replace with .orElseThrow() is the list cannot be empty