Search code examples
javaooplambdacomparatorjava-17

Java Comparator, comparing two doubles:


I use Java 17. Here is my code:

    public static class SortByPercentLike implements VideoSorterInterface {
        // define Lambda Function
        Comparator<Video> videoPercentLikeComparator = (a,b) -> {
            Double firstVideoPercentLike =  ((a.getLike() - a.getDislike())/ (double) a.getView());
            Double secondVideoPercentLike = ((b.getLike() - b.getDislike())/ (double) b.getView());
            return firstVideoPercentLike.compareTo(secondVideoPercentLike);
        };

        @Override
        public void sort(List<Video> videos) {
            videos.sort(Comparator.comparingDouble(videoPercentLikeComparator));
        }
    }

Comparator.comparingDouble(videoPercentLikeComparator) part gives me the error:

reason: no instance(s) of type variable(s) T exist so that Comparator<Video> conforms to ToDoubleFunction<? super T>

What is the problem

I have no idead what the error message means.


Solution

  • Unless I'm missing something, videos.sort(Comparator.comparingDouble(videoPercentLikeComparator)); should just be videos.sort(videoPercentLikeComparator);