Following is the code that gives me error "Bad return type in lambda expression: U cannot be converted to Integer". I do not understand why it needs Integer here as the keys are String.
public static void main(String[] args) {
String input="java is headache";
//-1st non repeated char using stream
String [] arr= input.split("");
List<String> myList= Arrays.asList(arr);
System.out.println(myList);
Map<String ,Long > myMap=myList.stream()
.collect(toMap(Function.identity(), String::length,
*(e1, e2) -> e2*, LinkedHashMap::new));
}
Highlighted area is the piece of code showing as incorrect in the IDE.
You have incorrectly declared the type of myMap
, which throws off the compiler:
Map<String, Integer> myMap = myList.stream()
.collect(Collectors.toMap(Function.identity(), String::length,
(e1, e2) -> e2, LinkedHashMap::new));
In general, the compiler often gives generics-related errors in the wrong place. It can help to separate out all parts, and explicitly typing them. In this case, I extracted the third parameter to a BinaryOperator<Integer>
variable, which pointed me to the real error.