PanTau
PanTau

Reputation: 73

How to sort list of object by time in java

What is the best way(FAST), how to sort list of my object by time (hour:minute:second);

i have list of object:

ArrayList<myObject> test = new ArrayList<>();

i have class:

public class myObject{

private final myTime actualTime;
private final String name;

public myObject(int hour, int minute, int second, String name){
     this.actualTime = new myTime(hour, minute, second);
     this.name = name;
}

private class myTime{
     private final hour, minute, second;
     public myTime(int hour, int minute, int second){
          this.hour=hour;
          this.minute = minute;
          this.second =second;
     }
}

}

Create test object:

test.add(new myObject(1, 0, 0, "Name1")); //1 hour, 0 minute, 0second...
test.add(new myObject(9, 0, 0, "Name2"));
test.add(new myObject(2, 0, 0, "Name3"));

//now i want sort, but i dont know how?
//i want print: Name2, Name3, Name1

I hope, you understand me, thank you for your advice.

EDIT1:

   @Override
        public int compareTo(Object t) {
            hourTmp = ((myTime) t).getHour();
            if (this.getHour() > hourTmp) {
                return 1;
            } else {
                return -1;
            }
        }

Upvotes: 0

Views: 3755

Answers (2)

Brett Okken
Brett Okken

Reputation: 6306

Use the Collections.sort method with a provided Comparator, or make your object implement Comparable.

Here is how you could create a Comparator in java 8 (after adding getters for time values):

Comparator.comparingInt(myTime::getHour)
              .thenComparingInt(myTime::getMinute)
              .thenComparingInt(myTime::getSecond);

Upvotes: 1

Voicu
Voicu

Reputation: 17850

You can make use of the Collections.sort(List) method which will perform a merge sort for you. But before you can use it you should make your custom class implement Comparable.

When implementing Comparable, you will need to implement the compareTo(myClass o) method and perform the comparison inside that method on whatever member you desire.

Upvotes: 2

Related Questions