Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Comparator using .reverseOrder() but with an inner class

I am creating a simple program to learn about the Java Comparator class. 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).

Here is my SongSort class which houses the sorting process etc.;

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;

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?

like image 255
James Morrison Avatar asked Apr 26 '11 11:04

James Morrison


People also ask

What is Comparator reverseOrder?

Comparator reverseOrder() method in Java with examples The reverseOrder() method of Comparator Interface in Java returns a comparator that use to compare Comparable objects in reverse of natural order. The returned comparator by this method is serializable and throws NullPointerException when comparing null.

How does Comparator work internally in Java?

Comparator , represents a component that can compare two objects so they can be sorted using sorting functionality in Java. When sorting e.g a Java List you can pass a Java Comparator to the sorting method. The Comparator is then used to compare the objects in the List during sorting.

Which class has Comparator () method?

Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element).

Can we use compareTo in Comparator?

In Java, we can implement whatever sorting algorithm we want with any type. Using the Comparable interface and compareTo() method, we can sort using alphabetical order, String length, reverse alphabetical order, or numbers. The Comparator interface allows us to do the same but in a more flexible way.


2 Answers

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

Edit July 2015

As this answer still gets some attention, here a small update:

With Java SE 8 it's becoming easier to create a reversed comparator:

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

And you can, of course, also use the Streams framework:

List<Song> sortedSongList = songList.stream() .sorted(Comparator.comparing(Song::getRating).reversed()) .collect(Collectors.toList()); 
like image 102
Puce Avatar answered Sep 27 '22 23:09

Puce


One way to implement an reverse order comparator is to implement an Compartor-Delegate that invert the comparator result (by changing the order).

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)); 
like image 22
Ralph Avatar answered Sep 28 '22 00:09

Ralph