错误:不兼容的类型:推理变量R具有不兼容的边界(Lambda java 8)

时间:2016-12-26 19:41:34

标签: java lambda java-8 bounds

我有一个Tree对象,其中包含Tree对象的子项(HashMap),依此类推。
我需要通过numericPosition变量过滤对象
例如:

Tree mapTreeRoot = new Tree("Root",0);      
int answer = 111;

mapTreeRoot
    .addNode("ChilldOfRoot",111)
    .addNode("ChildOfRootExample1",222)
    .addNode("ChildOfRootExample1Example2",333);

Tree treeObj  = mapTreeRoot
        .children
        .entrySet().stream()
        .filter(map -> answer == map.getValue().numericPosition)
        .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

在这种情况下,我应该得到一个由numericPosition进行过滤的Tree对象  树类

   public Tree(String name,int numericPosition) {
        this.name = name;
        this.numericPosition = numericPosition;
    }

    public Tree addNode(String key,int numericPosition) {
        Object hasKey =  children.get(key);
        if(hasKey == null) {
             children.put(key,new Tree(key,numericPosition)); 
        }

        return children.get(key);
    }

    public Tree getNode(String key) {
         Object hasKey =  children.get(key);
         if(hasKey != null) {
            return children.get(key);
        }
        return this;
    }

以防万一
我收到此错误:错误:不兼容的类型:推理变量R具有不兼容的边界

我一直关注这个例子,但它不适合我。 https://www.mkyong.com/java8/java-8-filter-a-map-examples/

此外,我尝试了HashMap<String,Tree> treeObj = mapTreeRoot ..但收到了相同的错误消息。

1 个答案:

答案 0 :(得分:4)

如果您想过滤一棵树,可以使用:

Tree treeObj = null;
Optional<Entry<String, Tree>> optional  = mapTreeRoot
        .children
        .entrySet().stream()
        .filter(map -> answer == map.getValue().numericPosition)
        .findAny();
if(optional.isPresent()){
    treeObj = optional.get().getValue();
}