[英]Java Comparator using .reverseOrder() but with an inner class
I am creating a simple program to learn about the Java Comparator class. 我正在创建一个简单的程序来了解Java Comparator类。 I have sorted an
Arraylist
into order but now I want to sort the list in descending order but am having problems in where to call the .reverseOrder()
method as I have used an inner class that implements Comparator<Song>
(song being a song class which houses getters and setter methods). 我已经按顺序对一个
Arraylist
了排序,但现在我想按降序对列表进行排序,但是我在调用.reverseOrder()
方法时遇到问题,因为我使用了一个实现Comparator<Song>
的内部类(歌曲是一首歌)容纳吸气剂和制定者方法的类)。
Here is my SongSort
class which houses the sorting process etc.; 这是我的
SongSort
课程,其中包含分类过程等。
import java.util.*;
import java.io.*;
public class SongSort
{
ArrayList<Song> songList = new ArrayList<Song>();
public void main(String[] args)
{
new SongSort().go();
}
class ArtistCompare implements Comparator<Song>
{
public int compare(Song one, Song two)
{
return one.getRating().compareTo(two.getRating());
}
}
public void go()
{
getSongs();
System.out.println(songList);
//Collections.sort(songList);
System.out.println(songList);
ArtistCompare artistCompare = new ArtistCompare();
Collections.sort(songList, artistCompare);
System.out.println(songList);
}
public void getSongs()
{
try{
File file = new File("SongListMore.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line = reader.readLine()) != null)
{
addSong(line);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void addSong(String lineToParse)
{
String [] tokens = lineToParse.split("/");
Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]);
songList.add(nextSong);
}
}
And here is my simple Song
class; 这是我简单的
Song
课;
public class Song //implements Comparable<Song>
{
private String title;
private String artist;
private String rating;
private String bpm;
public Song(String t, String a, String r, String b)
{
title = t;
artist = a;
rating = r;
bpm = b;
}
public String getTitle()
{
return title;
}
public String getArtist()
{
return artist;
}
public String getRating()
{
return rating;
}
public String getBpm()
{
return bpm;
}
public String toString()
{
return ("Title : " + title + "," + " Artist : " + artist + " Rating : " + rating);
}
}
Can anyone help me figure out where I will call the reverseOrder()
method in the SongSort
class, as it won't compile? 任何人都可以帮我弄清楚我将在
SongSort
类中调用reverseOrder()
方法,因为它不会编译?
ArtistCompare artistCompare = new ArtistCompare();
Collections.sort(songList, Collections.reverseOrder(artistCompare));
Edit July 2015 编辑2015年7月
As this answer still gets some attention, here a small update: 由于这个答案仍然受到一些关注,这里有一个小小的更新:
With Java SE 8 it's becoming easier to create a reversed comparator: 使用Java SE 8,创建反向比较器变得更加容易:
Comparator<Song> songRatingComparator = Comparator.comparing(Song::getRating);
Collections.sort(songList, songRatingComparator.reversed());
And you can, of course, also use the Streams framework: 当然,您也可以使用Streams框架:
List<Song> sortedSongList = songList.stream()
.sorted(Comparator.comparing(Song::getRating).reversed())
.collect(Collectors.toList());
One way to implement an reverse order comparator is to implement an Compartor-Delegate that invert the comparator result (by changing the order). 实现逆序比较器的一种方法是实现反转比较器结果的Compartor-Delegate(通过改变顺序)。
public class ReverseOrder<T> implements Comparator<T> {
private Comparator<T> delegate;
public ReverseOrder(Comparator<T> delegate){
this.delegate = delegate;
}
public int compare(T a, T b) {
//reverse order of a and b!!!
return this.delegate.compare(b,a);
}
}
So the only thing you need to do is to use this delegate. 所以你唯一需要做的就是使用这个委托。 For example:
例如:
Comparator myComparator = new myComparator();
List list = ...;
List reverse = new ArrayList(list);
//acceding
Collections.sort(list, myComparator);
//descending
Collections.sort(list, new ReverseOrder(myComparator));
Let's take a simple example we have a class Person with two fields name age and we want to sort an existing collection of persons based on their age so let's assume that we have a class Person with a constructor and add the persons into the list and then sort them unsing the method sort of collection : 让我们举一个简单的例子,我们有一个Person有两个字段名称age的类,我们想根据它们的年龄对现有的一组人进行排序,所以让我们假设我们有一个带有构造函数的Person,并将这些人添加到列表中然后排序他们没有方法的集合类:
Person bachiri = new Person (17,"bachiri");
Person taoufiq = new Person (14,"Taoufiq");
Person abderrahman = new Person (15,"abderrahman");
List<Person> persons = new ArrayList<>();
and this this the impelemtation of Agecomparable : 而这就是Agecomparable的阻碍:
class AgeComparator implements Comparator<Person>{
@Override
public int compare(Person person1, Person person2) {
return Integer.compare(person1.getAge(),person2.getAge());
}
}
the trick is to multiple the return method with -1 so the final result will be reversed: class AgeComparator implements Comparator{ 诀窍是使用-1复用return方法,以便最终结果反转:class AgeComparator实现Comparator {
@Override
public int compare(Person person1, Person person2) {
return -1 * Integer.compare(person1.getAge(),person2.getAge());
}
}
so now we can get a reversed result : 所以现在我们可以得到相反的结果:
Collection.sort (Persons, new AgeComparator());
If you need to use a Comparator which reverses the current order, just return a negative value in the compare
method. 如果需要使用反转当前顺序的比较器,只需在
compare
方法中返回负值 。
public class ComparatorInverse implements Comparator<Object> {
@Override
public int compare(Object lhs, Object rhs) {
return -1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.