我必须实现以下方法,该方法接受 Java Map 中的值元素并返回一组封装 Map 中的键和值对象的 pojo。
public Set<CacheElement<K, V>> searchByValue(V v);
CacheElement类如下:
public final class CacheElement<K, V> {
private final K k;
private final V v;
public CacheElement(K k, V v) {
super();
this.k = k;
this.v = v;
}
public K getK() {
return k;
}
public V getV() {
return v;
}
}
我编写了以下方法来查找 Map 中与传递的值对应的关键元素 Set。
public Set<CacheElement<K, V>> searchByValue(V v) {
Set<K> keySet = this.cacheMap.entrySet().stream()
.filter(entry -> entry.getValue().equals(v))
.map(entry -> entry.getKey())
.collect(Collectors.toSet());
return null;
}
我不知道如何编写 lambda 来传递 keySet
到 Map 并取回包含匹配的 CacheElement<K,V>
的 Set 。
我写了以下不完整的labmda:
Set<CacheElement<K, V>> elements = this.cacheMap.entrySet().stream()
.filter(entry ->keySet.contains(entry.getKey()))
.map(entry -> new CacheElement<K, V>(entry.getKey(), entry.getValue()));
我需要帮助来收集集合中新创建的 CacheElement 对象。
代码可在以下位置获取: https://github.com/abnig/ancache
谢谢
编辑1:
cacheMap 是
private Map<K, V> cacheMap = new ConcurrentHashMap<K, V>();
当我添加 .collect 操作数时
Set<CacheElement<K, V>> elements = cacheMap.entrySet().stream()
.filter(entry ->keySet.contains(entry.getKey()))
.map(entry -> new CacheElement<K, V>(entry.getKey(), entry.getValue())
.collect(Collectors.toSet()));
然后我收到以下错误:
Type mismatch: cannot convert from Stream<Object> to Set<CacheElement<K,V>> line 92 Java Problem
The method collect(Collectors.toSet()) is undefined for the type CacheElement<K,V> line 95 Java Problem
第 92 行是:Set<CacheElement<K, V>> elements = cacheMap.entrySet().stream()
第 95 行是:collect(Collectors.toSet()))
编辑2
最佳答案
您主要缺少collect
(toSet) 和返回
结果。您还可以确保将该逻辑与收集和返回结合起来执行完整的操作:
public Set<CacheElement<K, V>> searchByValue(V v) {
return this.cacheMap.entrySet().stream() // assuming Map<K, V> cacheMap
.filter(entry -> entry.getValue().equals(v)) // filter entries with same value 'v'
.map(entry -> new CacheElement<>(entry.getKey(), entry.getValue())) // map key and value to CacheElement
.collect(Collectors.toSet()); // collect as a Set
}
关于使用值搜索 Java Map 的 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795819/