1

I am having an range of time , i want to sort the time based on the starting time For Ex:

Range = {[3,5] , [1,10] ,[6,7] ,[4,10]}
After sorting
{ [1,10] , [3,5] , [4,10] , [6,10]}

How can it be done using Collections.sort or anyother method.
Does i have to define a class to sort i.e

class interval{
int start;
int end;
}

i have above structure i want to sort it with respect to start;
i.e Collections.sort(interval) // with respect to start;

0

4 Answers 4

3

Use Collections.sort with a custom Comparator<T>:

Collections.sort(times, new Comparator<interval>() {
    public int compare(interval a, interval b) {
        int res = Integer.compare(a.start, b.start);
        if (res != 0) return res;
        return Integer.compare(a.end, b.end);
    }
});

Another way of coding this would be implementing the Comparable<T> interface in the interval class.

Sign up to request clarification or add additional context in comments.

Comments

1

You have 2 options either implement Comparable for your class or use Comparator. Using java 8 syntax it will look like this

Collections.sort(list, (o1, o2) -> {
            int start =  Integer.compare(o1.getStart(), o2.getStart());
            int end =  Integer.compare(o1.getEnd(), o2.getEnd());
            if (start != 0) return start;
            else return end;
        });

To implement Comparable you should do like this

    class interval implements Comparable<interval> {
@Override
    public int compareTo(interval o) {
        //the same logic as used in compartor
    }
}

Comments

0

Just a hint won't be writing code for you until you show some more effort

Implement you own Comparator and pass this as an argument to Collections.sort

Another thing to consider make sure you don't do new Comparator as this will keep making new instances of you comparator. You want to make it singleton.

2 Comments

I completely agree with you but this is not an answer. It's more like a comment! I'll not flag you so far.
I put is as an answer cause i said I would put code if OP showed more effort. Next time will put it up in comment.
0

To build on top of dasblinkenlight's answer, to achieve this by implementing the Comparable interface in the interval, do this

class interval implements Comparable<interval> {
  // old code
  public int compare(interval a, interval b) {
    int res = Integer.compare(a.start, b.start);
    if (res != 0) return res;
    return Integer.compare(a.end, b.end);
  }
}

Note that it is customary to use capital case for class name, so change 'interval' to Interval.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.