【发布时间】:2018-12-15 17:57:33
【问题描述】:
我必须实现以下方法,该方法接收 Java Map 中的 value 元素并返回 Map 中封装 key 和 value 对象的一组 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中找到传递的值对应的键元素集合。
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
谢谢
Edit-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()))
Edit-2
【问题讨论】:
-
你不只是在寻找
.collect(Collectors.toSet());还是我错过了什么? -
@Aomine - 添加收集时出现错误。请参考编辑-1部分