加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

通过使用Java 8流进行分组

发布时间:2020-12-14 19:26:15 所属栏目:Java 来源:网络整理
导读:我正在使用Java 8 Streams,我有一个类似于以下的类: public class ShareDao { private String senderId; private String receiverId; public String getSenderId() { return senderId; } public String sharingMode(){ return this.receiverId != null !thi

我正在使用Java 8 Streams,我有一个类似于以下的类:

public class ShareDao {
    private String senderId;
    private String receiverId;

    public String getSenderId() {
        return senderId;
    }

    public String sharingMode(){
        return this.receiverId != null && !this.receiverId.trim().isEmpty() ? "incoming" : "outgoing";
    }
}

现在我想做的是,我想:

>过滤出senderId无效的记录(使用Map<>查找)
>将集合按senderId分组,然后再按shareMode对其进行分组.

下面是我的代码:

Map<String,Map<String,List<ShareDao>>> p = records.stream()
            .filter(shared -> userMap.containsKey(shared.getSenderId()))
            .collect(Collectors.groupingBy(ShareDao::getSenderId),Collectors.groupingBy(ShareDao::sharingMode,Function.identity()));

它抛出了错误:

Error:(105,90) java: no suitable method found for groupingBy(Share[…]gMode,java.util.function.Function)
method java.util.stream.Collectors.groupingBy(java.util.function.Function) is not applicable
(cannot infer type-variable(s) T,K
(actual and formal argument lists differ in length))
method java.util.stream.Collectors.groupingBy(java.util.function.Function,java.util.stream.Collector) is not applicable
(no instance(s) of type variable(s) T exist so that java.util.function.Function conforms to java.util.stream.Collector)
method java.util.stream.Collectors.groupingBy(java.util.function.Function,java.util.function.Supplier,java.util.stream.Collector) is not applicable
(cannot infer type-variable(s) T,K,D,A,M
(actual and formal argument lists differ in length))

当Intellij Idea引发错误时

无法从静态上下文引用非静态方法

最佳答案
根据您要实现的目标

  • Filter out the records where senderId is invalid (using a Map<>
    lookup)
  • Group the collection by the senderId and then further group them by the shareMode.

您可以改用:

Map<String,List<ShareDao>>> p = records.stream()
        .filter(shared -> userMap.containsKey(shared.getSenderId())) // filter records
        .collect(Collectors.groupingBy(ShareDao::getSenderId,// grouping by senderId
                Collectors.groupingBy(ShareDao::sharingMode)));  //further grouping by sharingMode

注意:

> groupingBy属性可将值汇总为列表.
>在收集器中定义的收集器,因为它与您的尝试不同.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读