2016-12-26 550 views
2

我有一个包含树对象的儿童(HashMap中)等上的树对象。
我需要通过numericPosition变量来过滤对象。

例如:错误:不兼容的类型:推断变量R具有不相容界限(拉姆达的java 8)

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
树类过滤一树对象

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 ..但得到了同样的错误信息。

+0

你流操作返回的地图。该返回值与不具有映射的treeObj不兼容。 – Calculator

+0

@Calculator我试图使用HashMap treeObj = mapTreeRoot ...仍然是同样的问题。 – Oyeme

+1

当'answer'已经*了'String'时,'(“”+ answer)'什么是? – Andreas

回答

3

如果要筛选整整一棵树,你可以使用:

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(); 
} 
+0

我得到这个错误:。错误:不兼容的类型:条目无法转换为可选<条目> – Oyeme

+1

@Oyeme现在它应该工作。 'findAny()'后面的'get()'在我的答案中是错误的。 – Calculator

+0

干杯。这就是我想要的! – Oyeme