我对java流来说还很陌生,正在尝试确定如何从列表列表中的每个列表中找到最大值,并以包含每个子列表中的最大值的单个列表结尾。
我可以使用for
循环和stream
这样来完成此操作:
// databaseRecordsLists is a List<List<DatabaseRecord>>
List<DatabaseRecord> mostRecentRecords = new ArrayList<>();
for (List<DatabaseRecord> databaseRecords : databaseRecordsLists) {
mostRecentRecords.add(databaseRecords.stream()
.max(Comparator.comparing(DatabaseRecord::getTimestamp))
.orElseThrow(NoSuchElementException::new));
}
我研究了flatMap
api,但最后只得到了所有DatabaseRecord
对象的单个映射,在这里我需要每个单独列表的最大值。
是否有更干净的方法来实现这一目标?
您不需要flatMap
。创建一个Stream<List<DatabaseRecord>>
,并将List<DatabaseRecord>
的每个Stream
映射到最大元素。然后将所有最大元素收集到输出List
中。
List<DatabaseRecord> mostRecentRecords =
databaseRecordsLists.stream()
.map(list -> list.stream()
.max(Comparator.comparing(DatabaseRecord::getTimestamp))
.orElseThrow(NoSuchElementException::new))
.collect(Collectors.toList());