我有一个“文章”列表,我需要对其进行分组并获取最新的组。假设我的对象是
private interface Article {
Date getCreated();
String getAuthor();
}
我需要从最近的组中找到唯一的名称。这是我想出的解决方法,但我不确定时间复杂度或注意事项。
Set<String> previous = Optional.ofNullable(articles
.stream()
.collect(Collectors.groupingBy(Article::getCreated, () -> new TreeMap<>(Comparator.reverseOrder()), Collectors.toList()))
.firstEntry())
.map(entries -> entries.getValue()
.stream()
.map(event -> event.getAuthor())
.collect(Collectors.toSet()))
.orElse(Collections.emptySet());
有没有更简单的方法来做到这一点?
最佳答案
因为您尝试使用包装的 Optional
处理的唯一情况是当前代码中的空文章列表。您可以通过检查来简化它,例如:
private static Set<String> authorsOfMostRecentArticles(List<Article> articles) {
if (articles.isEmpty()) return Collections.emptySet();
return articles.stream()
.collect(Collectors.groupingBy(Article::getCreated,
TreeMap::new, Collectors.toList()))
.lastEntry().getValue() // slight change
.stream()
.map(Article::getAuthor)
.collect(Collectors.toSet());
}
另一方面,如果您还想确保逻辑中有额外的 filter
,那么找到 lastEntry
并进一步处理会更简单。
private static Set<String> authorsOfMostRecentArticles(List<Article> articles) {
Map.Entry<Date, List<Article>> mostRecentEntryOfArticles = articles.stream()
.filter(java.util.Objects::nonNull) // if articles could be null
.filter(article -> article.getCreated() != null) // if getCreated could be null as well
.collect(Collectors.groupingBy(Article::getCreated,
TreeMap::new, Collectors.toList()))
.lastEntry();
return mostRecentEntryOfArticles == null ? Collections.emptySet() :
mostRecentEntryOfArticles.getValue().stream()
.map(Article::getAuthor)
.collect(Collectors.toSet());
}
简而言之,不需要将代码包装在 Optional.of..
中,这也是将条目作为 null
返回的意图.
关于java - 在分组操作中获得最后一组的推荐方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62704057/