我在Java中使用流API进行泛型映射时遇到了麻烦。我有一个通过以下方式扩展LinkedHashMap的地图
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private int size;
public LRUCache(int size) {
super(size);
this.size = size;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > size;
}
public LRUCache<K, V> collect() {
return entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)
);
}
}
我正在尝试一个虚拟方法collect
,该方法实际上将流式传输到entrySet上,对其应用一些过滤器,然后返回一个新的LRUCache,但是Collectors.toMap
继续抛出错误,它表示]]
“不能从静态上下文中引用非静态方法”
我知道这是Collectors.toMap泛型定义的问题。但是,我无法找出正确的泛型来摆脱错误并实现流和收集功能]
我在Java中使用流API进行泛型映射时遇到了麻烦。我有一个通过以下方式扩展LinkedHashMap的映射:公共类LRUCache
LinkedHashMap
在其实现中包括一个无参数的构造函数,该构造函数充当toMap
收集操作的提供者
您似乎只是想复制您的地图/缓存。不需要流来执行此操作。