java - 在分组操作中获得最后一组的推荐方法是什么?

标签 java java-stream

我有一个“文章”列表,我需要对其进行分组并获取最新的组。假设我的对象是

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/

相关文章:

java - 我如何在 TabHosts 中重新填充我的 ListView ?

java - android如何制作内 View 圆形形状如图所示

java - 优化这些用于在 Java 8 中创建 HashMap 的嵌套 for 循环的最佳方法是什么?

java - Stream.map(...) 和 Collectors.mapping(...) 有什么区别?

java - 从行列表中获取数组?

java - 如何在java中翻转句子中的两个单词

内存不足时的 Java EE 堆转储

Java Lambda 流列表<用户> 到映射<角色,列表<用户>>

Java 8 - Lambda 表达式将 List<String> 转换为 List<DTO>

java - 有没有一种方法可以使用Java 8中的流来合并列表中的重复数字?