【问题标题】:Lambda expression to search a Java Map using value使用值搜索 Java Map 的 Lambda 表达式
【发布时间】: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&lt;K,V&gt; 的 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&lt;CacheElement&lt;K, V&gt;&gt; elements = cacheMap.entrySet().stream()

第 95 行是:collect(Collectors.toSet()))

Edit-2

【问题讨论】:

  • 你不只是在寻找 .collect(Collectors.toSet()); 还是我错过了什么?
  • @Aomine - 添加收集时出现错误。请参考编辑-1部分

标签: lambda java-8


【解决方案1】:

您主要缺少collect (toSet) 和returning 结果。您还可以确保将该逻辑与 collect 和 return 结合起来执行完整的操作:

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
}

【讨论】:

  • 添加收集时出现错误。请参考编辑-1部分
  • 好的@AbNig,你能用你的cacheMap 的类型更新问题吗?
  • 添加评论和github url
  • @AbNig 上面共享的代码与您提供的详细信息编译得很好。不确定问题详细信息是否完整,否则对于 MCVE。
  • @AbNig 在您显示的屏幕截图中很好,存在语法错误,您没有使用 ) 括号关闭 map 中间方法,您需要再删除一个 @987654327 @收集后。你为什么不直接复制这里提供的代码并把它过去(我相信这在语法上是正确的)......
猜你喜欢
  • 1970-01-01
  • 2015-11-19
  • 2015-10-07
  • 2011-03-27
  • 1970-01-01
  • 2020-07-16
  • 2017-06-13
  • 2015-03-09
  • 2018-11-02
相关资源
最近更新 更多