更具体地说,我对馆藏排序有疑问
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]
应该这样做的方法(在MovieStorage类中):
public Set<Movie> getCatalogue(Comparator<Movie> comp){
List<Movie> sett = new ArrayList<>(this.movieList);
sett.sort(comp);
return new HashSet<>(sett);
}
实现比较器的类:
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()));
我一直在寻找StackOverflow和其他网站,但是我注意到每个人都根据1个参数对它进行排序(这对我也不起作用),同时,代码与我的代码几乎相同。 ..
感谢您的帮助:)
答案 0 :(得分:2)
创建比较器的更紧凑的方法:
spyder --reset
然后Comparator<Movie> comparator =
Comparator.comparing(Movie::getName).thenComparing(Movie::getAuthor);
Set<Movie> movies = new TreeSet<>(comparator);
movies.addAll(movieList);
会按排序顺序进行迭代。
要添加到TreeSet
类中,请执行以下操作:
Movie
然后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