error: incompatible types: inference variable R has incompatible bounds (Lambda java 8)

4k views Asked by At

I have a Tree object that contains children (HashMap) of Tree objects and so on.
I need to filter objects by numericPosition variable.

For example:

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()));

In this case I should get a Tree object filtered by numericPosition
Tree class

   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;
    }

Just in case
I got this error: error: incompatible types: inference variable R has incompatible bounds

I have been following by this example but it's not working for me. https://www.mkyong.com/java8/java-8-filter-a-map-examples/

Also I have tried HashMap<String,Tree> treeObj = mapTreeRoot.. but got the same error message.

1

There are 1 answers

3
Calculator On BEST ANSWER

If you want to filter for exactly one tree you can use:

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