0

I have a java arraylist:

List<Log> logs = new ArrayList<Log>();

Log class has the following attributes:

String type;
int num;
Date date;

What would be a good way to order the logs list by date?

user3552506
  • 45
  • 1
  • 1
  • 7
  • I refer you to this: [http://stackoverflow.com/questions/4066538/sort-an-arraylist-based-on-an-object-field](http://stackoverflow.com/questions/4066538/sort-an-arraylist-based-on-an-object-field) – Justice Oct 27 '15 at 02:32
  • 1
    those answers are too old. there are better solutions in java8. – ZhongYu Oct 27 '15 at 02:34

1 Answers1

0

You can implements a Comparator interface as the followings:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class Main {
    public static void main(String arg[]) {
        List<Log> logs = new ArrayList<Log>();
        logs.sort(new CustomComparator());
    }
}

class CustomComparator implements Comparator<Log> {
    @Override
    public int compare(Log o1, Log o2) {
        return o1.date.compareTo(o2.date);
    }
}

class Log {
    String type;
    int num;
    Date date;
}

please notice using the sort function

William Kinaan
  • 28,059
  • 20
  • 85
  • 118