27

我正在创建一个简单的程序来了解 Java Comparator 类。我已经按Arraylist顺序对列表进行了排序,但是现在我想按降序对列表进行排序,但是.reverseOrder()由于我使用了一个实现的内部类Comparator<Song>(song 是一个包含 getter 和 setter 方法的歌曲类),所以在调用该方法的位置有问题。

这是我的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);

    }

}

这是我的简单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);
    }
}

谁能帮我弄清楚我将reverseOrder()在类中调用该方法的位置SongSort,因为它不会编译?

4

4 回答 4

82
ArtistCompare artistCompare = new ArtistCompare();
Collections.sort(songList, Collections.reverseOrder(artistCompare));

编辑 2015 年 7 月

由于这个答案仍然受到关注,这里有一个小的更新:

使用 Java SE 8,创建反向比较器变得更加容易:

Comparator<Song> songRatingComparator = Comparator.comparing(Song::getRating);
Collections.sort(songList, songRatingComparator.reversed());

当然,您也可以使用 Streams 框架:

List<Song> sortedSongList = songList.stream()
.sorted(Comparator.comparing(Song::getRating).reversed())
.collect(Collectors.toList());
于 2011-04-26T11:29:27.370 回答
6

实现逆序比较器的一种方法是实现一个 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);
  }
}

所以你唯一需要做的就是使用这个委托。例如:

  Comparator myComparator = new myComparator();
  List list = ...;
  List reverse = new ArrayList(list);

  //acceding
  Collections.sort(list, myComparator);

  //descending
  Collections.sort(list, new ReverseOrder(myComparator));
于 2011-04-26T11:24:54.650 回答
4

让我们举一个简单的例子,我们有一个 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<>();

这就是 Agecomparable 的实现:

class AgeComparator implements Comparator<Person>{


    @Override
    public int compare(Person person1, Person person2) {
        return Integer.compare(person1.getAge(),person2.getAge());
    }


}

诀窍是将返回方法与 -1 相乘,因此最终结果将相反:class AgeComparator implements Comparator{

    @Override
    public int compare(Person person1, Person person2) {
        return -1 * Integer.compare(person1.getAge(),person2.getAge());
    }


}

所以现在我们可以得到相反的结果:

Collection.sort (Persons, new AgeComparator());
于 2017-05-20T22:19:20.423 回答
-8

如果您需要使用反转当前顺序的比较器,只需在方法中返回一个负值compare

public class ComparatorInverse implements Comparator<Object> {
   @Override
   public int compare(Object lhs, Object rhs) {
      return -1;
   }
}
于 2013-05-08T18:37:24.227 回答