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

Sort String Length, but reversed (longest String first)

I have to do an excercise where i have to write a method orderQuestionsByLength(), which should sort questions by its length (descending)

the following code works (but it’s not sorted descending):

`public void orderQuestionsByLength(){
        Collections.sort(questions,Comparator.comparing(question -> question.getText().length())); 
        for (Question question : questions){                                                       
            System.out.println(question);
        }
    }`

as soon as i add .reversed() my IDE throws an error Cannot resolve method ‘getText’ in ‘Object’ even though i have a method getText() and it worked before adding .reversed()

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

it drives me crazy, bc i don’t know how to solve the problem, gpt says my code is right (not saying that i should rely on gpt, but i have another method where i sort integers descending, where i used reversed() without any problems

>Solution :

This can sometimes happen because the Comparator.comparing method can’t correctly infer the type of the lambda parameter when it’s chained with .reversed().

To solve this issue, you can provide explicit type information in the lambda expression. Here’s how you can modify your orderQuestionsByLength method with (String question) -> ….

public void orderQuestionsByLength() {
    Collections.sort(questions, Comparator.comparing((Question question) -> question.getText().length()).reversed()); 
    for (Question question : questions) {                                                       
        System.out.println(question);
    }
}
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