2016-12-26 553 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