0

I have a quite hard time to get my code running. I have a generic method, that should sort and remove all duplicates from a given List. The items in the List, for example, String, all implement the Comparable interface. Unfortunately, the code is not compiling and I don't understand why...

public static <T> List<T> distinctAndSort(List<T> s) {
    List<T> list = s.stream().distinct().collect(Collectors.toList());
    Collections.sort(list); //Error
    return list;
}

This is what I got so far. Why can't I put my List<T> into sort? (The method sort(List<T extends Comparable<? super T>>) in the type Collections is not applicable to the arguments (List<T>).

In order to make my function work, what am I missing? Thx for every help

0

2 Answers 2

10

Declare your type variable as:

<T extends Comparable<? super T>>

This restricts your method only to be called with a type which implements Comparable, and thus you can call Collections.sort without an explicit Comparator.

Alternatively, you could provide a Comparator<? super T> as an additional parameter to the method, and pass it to Collections.sort.

Additionally, note that you can do the sorting with the stream API:

return s.stream()
    .distinct()
    .sorted()
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

1

According to the docs, Collections.sort(List<T>) must be a list of Comparables, or you must supply a Comparator<T>. You can change your signature:

public static <T extends Comparable<? super T>> List<T> distinctAndSort(List<T> s)

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List) https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.