Search code examples
javaguava

Creating heterogenous list of lists in Java


I have the following code

        List<Integer> startnodes = ImmutableList.of(397251,519504,539122,539123,539124,539125);
        List<Integer> endnodes = ImmutableList.of(539126,539127,539142,539143,539144,539145);
        List<String> rp = ImmutableList.of("Knows","Knows","Knows","Knows2","Knows2","Knows2");
        Map<String,Value> parameters =
                  ImmutableMap.of("rels",ImmutableList.of(startnodes,endnodes,rp));

The compiler throws the following error at the last line.

Type mismatch: cannot convert from ImmutableMap<String,ImmutableList<List<? 
extends Object&Comparable<?>&Serializable>>> to Map<String,Value>

My main confusion is that the value for the key here is a heterogenous list, so what should be the type of the key to satisfy the compiler?. I am relatively new to Java and any suggestions are welcome. Thanks!


Solution

  • ImmutableList.of(startnodes,endnodes,rp) needs to infer a type that will satisfy both List<Integer> and List<String> because generics in Java are invariant the only type that satisfies it is List<?>. So you can assign it to:

    List<List<?>> list = ImmutableList.of(startnodes,endnodes,rp);
    

    And your Map needs to be defined as:

    Map<String,List<List<?>>> parameters = ImmutableMap.of("rels",ImmutableList.of(startnodes,endnodes,rp));