Java 8 generics and type inference problem

I am trying to convert this:

static Set<String> methodSet(Class<?> type) { Set<String> result = new TreeSet<>(); for(Method m : type.getMethods()) result.add(m.getName()); return result; } 

Which compiles just fine, to a more modern version of Java 8 threads:

 static Set<String> methodSet2(Class<?> type) { return Arrays.stream(type.getMethods()) .collect(Collectors.toCollection(TreeSet::new)); } 

What causes the error message:

 error: incompatible types: inference variable T has incompatible bounds .collect(Collectors.toCollection(TreeSet::new)); ^ equality constraints: String,E lower bounds: Method where T,C,E are type-variables: T extends Object declared in method <T,C>toCollection(Supplier<C>) C extends Collection<T> declared in method <T,C>toCollection(Supplier<C>) E extends Object declared in class TreeSet 1 error 

I can understand why the compiler will have problems with this - there is not enough type information to figure out the conclusion. I do not see how to fix it. Somebody knows?

+5
source share
1 answer

The error message is not very clear, but the problem is that you are not collecting the name of the methods other than the methods themselves.

In other words, you are missing the mapping from Method to its name:

 static Set<String> methodSet2(Class<?> type) { return Arrays.stream(type.getMethods()) .map(Method::getName) // <-- maps a method to its name .collect(Collectors.toCollection(TreeSet::new)); } 
+11
source

Source: https://habr.com/ru/post/1240645/


All Articles