Example to sort an arraylist of objects by a property

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

 

class HockeyPlayer {
    public final int goalsScored;
    // ...
};

List<HockeyPlayer> players = // ...

Collections.sort(players, new Comparator<HockeyPlayer>() {
    @Override 
    public int compare(HockeyPlayer p1, HockeyPlayer p2) {
        return p1.goalsScored - p2.goalsScored; // Ascending
    }
});
class PlayerComparatorByRating implements Comparator<Player> {
    @Override
    public int compare(Player o1, Player o2) {
        return o1.getRating() - o2.getRating();
    }
}

class PlayerComparatorByName implements Comparator<Player> {
    @Override
    public int compare(Player o1, Player o2) {
        return o1.getName().compareTo(o2.getName());
    }
}
Collections.sort(list, new PlayerComparatorByRating());
System.out.println(list);
Collections.sort(list, new PlayerComparatorByName());
System.out.println(list);
List<Book> books = new ArrayList<Book>();
Collections.sort(books, new Comparator<Book>(){
    public int compare(Book o1, Book o2) {
        return o1.name.compareTo(o2.name);
    }
});
Example to sort an arraylist of objects by a property

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s