基于class排序的集合排序,实现了Comparator

Collection sort that sort based on class that implements Comparator

我对集合排序有疑问,更具体地说

Output:
[B_Author: Movie_X, A_Author: Movie_A, A_Author: Movie_B]
Should Be:
[A_Author: Movie_A, A_Author: Movie_B, B_Author: Movie_X]

应该这样做的方法(在 class MovieStorage 中):

public Set<Movie> getCatalogue(Comparator<Movie> comp){
        List<Movie> sett = new ArrayList<>(this.movieList);
        sett.sort(comp);
        return new HashSet<>(sett);
    }

Class 实现比较器:

public class MovieComparator implements Comparator<Movie>
{
    @Override
    public int compare(Movie a, Movie b) {
        if (a.getName().compareTo(b.getName()) == 0){
            return a.getAuthor().compareTo(b.getAuthor());
        }
        return a.getName().compareTo(b.getName());
    }
}

调用的方法:

System.out.println(movieStorage.getCatalogue(new MovieComparator()));

我一直在浏览 Whosebug 和其他网站,但我注意到每个人都根据 1 个参数对其进行排序(这对我也不起作用),同时代码与我的代码几乎相同是...

提前感谢您的帮助:)

一种更紧凑的创建比较器的方法:

Comparator<Movie> comparator =
    Comparator.comparing(Movie::getName).thenComparing(Movie::getAuthor);

Set<Movie> movies = new TreeSet<>(comparator);
movies.addAll(movieList);

并且 TreeSet 按排序顺序迭代。

添加到Movie class:

public static class Movie implements Comparable<Movie> {
    private static final Comparator<Movie> COMPARATOR =
        Comparator.comparing(Movie::getName).thenComparing(Movie::getAuthor);

    ...

    @Override
    public int compareTo(Movie other) {
        return COMPARATOR.compare(this, other);
    }
}

那么 TreeSet 不需要指定比较器:

Set<Movie> movies = new TreeSet<>(movieList);