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
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>
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());
According to the docs, Collections.sort(List<T>)
must be a list of Comparable
s, 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.