我正在与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";
}
}
现在我想做的是,我想:
下面是我的代码:
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()));
它抛出了错误:
错误:(105,90)java:找不到适合groupingBy(Share [...] gMode,java.util.function.Function)的合适方法 方法java.util.stream.Collectors.groupingBy(java.util.function.Function)不适用 (无法推断类型变量T,K (实际和正式参数列表的长度不同) 方法java.util.stream.Collectors.groupingBy(java.util.function.Function,java.util.stream.Collector)不适用 (不存在类型变量T的实例,因此java.util.function.Function符合java.util.stream.Collector) 方法java.util.stream.Collectors.groupingBy(java.util.function.Function,java.util.function.Supplier,java.util.stream.Collector)不适用 (无法推断类型变量T,K,D,A,M (实际和正式论点列表的长度不同)
Intellij Idea
引发错误
Non-Static method cannot be referenced from static context
答案 0 :(得分:2)
根据您要实现的目标
- 过滤掉senderId无效的记录(使用Map <>
查找)- 通过senderId对集合进行分组,然后通过shareMode对它们进行进一步分组。
您可以改用:
Map<String, 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
属性可将值汇总为List
。
在Collector
中定义的collect
与您的尝试有所不同。