-1

I have an ArrayList containng Objects which contain three values, now I'd like to sort them by these values:

List<AvailablePeriod> periodList = new ArrayList<AvailablePeriod>

And an AvailablePeriod object contains:

DateTime start
DateTime end
int id

I'd like to have the objects in the list sorted first by start, than end and last by id.

Can't get the sorting figured out..

Luc
  • 617
  • 3
  • 10
  • 18
  • 1
    I believe that this post can solve your problem: [http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property][1] [1]: http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – gred Mar 11 '13 at 11:22
  • My problem is the multiple value part, no need to downvote before giving a chance to explain -_- – Luc Mar 11 '13 at 11:29

2 Answers2

0

Write a comparator as below

   public class MyComparator implements Comparator<AvailablePeriod> {
    @Override
    public int compare(AvailablePeriod o1, AvailablePeriod o2) {
        int result = o1.getStart().compareTo(o2.getStart());
        if (result == 0) {
            result = o1.getEnd().compareTo(o2.getEnd());
        }
        if (result == 0) {
            result = Integer.valueOf(o1.getId()).compareTo(o2.getId());
        }
        return result;
    }
   }

Then use Collection.sort method

List<AvailablePeriod> periodList = new ArrayList<AvailablePeriod>
Collections.sort(periodList , new MyComparator());
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
0

class xyz implements Comparable {
    DateTime start;
    DateTime end;
    int id;

@Override
public int compareTo(xyz o) {
    if (this.start.isBefore(o.start)) {
        return -1;

    } else if (o.start.isBefore(o.start)) {

        return -1;

    } else {
        if (this.end.isBefore(o.end)) {
            return -1;

        } else if (o.end.isBefore(this.end)) {

            return 1;

        } else {
            if (this.id > o.id) {
                return 1;

            } else if (this.id < o.id) {

                return -1;

            } else {
                return 0;
            }
        }

    }

}

}

You can write something like this.And then use collections.sort(list)

Pranav Kevadiya
  • 519
  • 1
  • 6
  • 17