1
votes

I am running into an issue in java 8 where it is not allowing me to collect objects when using a cast.

definitions.stream()
           .map(Definition.class::cast)
           .map((Definition definition) -> { 
               WonderfulDefinition wd = new WonderfulDefinition();
               wd.name(definition.getName());
               //etc
               return wd;
           }).collect(Collectors.toList())

And I am getting the compiler error:

Error:(71, 23) java: incompatible types: inference variable T has incompatible bounds equality constraints: java.util.List lower bounds: java.lang.Object

Any help would be appreciated.

Updated:

import java.util.*;
import java.util.stream.*;

class Driver {
    public static void main(String[] args) {
        List definitions = new ArrayList<>();
        definitions.add(new Definition());
        definitions.add(new Definition());

        List<WonderfulDefinition> list =
                definitions.stream()
                        .map(Definition.class::cast)
                        .map((Definition definition) -> {
                            WonderfulDefinition wd = new WonderfulDefinition();
                            wd.name(definition.getName());
                            //etc
                            return wd;
                        }).collect(Collectors.toList());

        System.out.println(list);
    }
}
class Definition {
    private String name;

    public String getName() {
        return name;
    }
    public void name(String name) {
        this.name = name;
    }
}
class WonderfulDefinition extends Definition {
}
1
What type contains your initial definitions list ?Schidu Luca
Object unfortunately. It's coming from a 3rd party lib that returns definitions as List with no type. i.e. dictionary.getDefinitions() returns just Listuser1870035
What type the List variable has? It probably marking that part, since there's no other mentions of lists.M. Prokhorov
Please update your question with an MCVE which reproduces the issue you're having. Here's an example where your code as-is appears to work: ideone.com/IPoexaRadiodef
Hi Radiodef, I updated it. Due to list being just "List" (lib code can't change it) without a type specifier (object or otherwise) it is failing.user1870035

1 Answers

2
votes

The problem is that your List is untyped. In this case, simply hint the compiler by performing a cast:

((List<Object>) definitions).stream()
      .map(Definition.class::cast)
      .map(definition -> {
          WonderfulDefinition wd = new WonderfulDefinition();
          wd.name(definition.getName());
          //etc
          return wd;
      }).collect(Collectors.toList());

keep in mind that something like this is perfectly valid:

List definitions = Arrays.asList(new Definition());
List<Object> d = definitions;