我有一个自定义对象列表:
List<CustomObject> customObjects;
我想从中提取所有具有最早日期时间值集的对象。
所以类看起来像这样:
class CustomObject {
LocalDateTime date;
public LocalDateTime getDateTime() {
return date;
}
}
并且我能够使用这样的自定义比较器函数成功地在列表中找到最早日期的对象:
private static LocalDateTime getDate(CustomObject customObject) {
return customObject.getDateTime();
}
CustomObject customObjectMin = customObjects.stream().
min(Comparator.comparing(MyUtilClass::getDate));
但是,可以有多个具有相同日期的自定义对象,但在使用 min
的情况下似乎无法获得多次出现。是否有一个简单的解决方案来查找列表中设置最早日期的所有对象?像这样:
List<CustomObject> customObjectsMin = customObjects.stream().
minWithAllOccurences(Comparator.comparing(MyUtilClass::getDate));
最佳答案
你可以做两个选择。
- 一个找到最小日期
- 找到那个日期的人
例如
LocalDate min = customObjects.stream()
.map(CustomObject::getDateTime)
.min(Comparator.naturalOrder());
List<CustomObject> objs = customObjects.stream()
.filter(c -> min.equals(c.getDateTime()))
.collect(Collectors.toList());
或者您可以将 Collectors.groupingBy 用于 TreeMap 并获取第一个条目。
关于java - 从列表中检索多个最小出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51735944/