This tutorial shows you way to Sort List of Objects using Comparable
example.
Related Post: Java Sort List of Objects with Comparator
Contents
I. Overview
1. Goal
Sort list of three MyDate(year,month,day)
objects.
2. Steps to do
– Implement Comparable
interface for the class of objects you want to sort.
– Override compareTo(T other)
method and:
+ return zero if this object is equal other
+ a negative number if it’s less than other
+ a positive number if it’s greater than other
– Use Collections.sort()
method.
III. Practice
1. Create Class for objects to be sorted
package com.grokonez.comparable; public class MyDate implements Comparable<MyDate> { private int year; private int month; private int day; public MyDate(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } @Override public String toString() { return "MyDate [year=" + year + ", month=" + month + ", day=" + day + "]"; } @Override public int compareTo(MyDate other) { if (this.getYear() != other.getYear()) return this.getYear() - other.getYear(); else if (this.getMonth() != other.getMonth()) return this.getMonth() - other.getMonth(); return this.getDay() - other.getDay(); } } |
2. Create test function
package com.grokonez.comparable; import java.util.Arrays; import java.util.Collections; import java.util.List; public class MainApp { public static void main(String[] args) { System.out.println("=== Sort using Comparable ==="); List<MyDate> myDates = Arrays.asList( new MyDate(2010, 4, 3), new MyDate(2006, 5, 16), new MyDate(2007, 6, 29)); Collections.sort(myDates); myDates.forEach(System.out::println); } } |
4. Run & check Result
=== Sort using Comparable === MyDate [year=2006, month=5, day=16] MyDate [year=2007, month=6, day=29] MyDate [year=2010, month=4, day=3] |