Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I do not have idea what am doing wrong. in the below stream api related code snippet

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading