Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Sorting Array by time

First: I use a Array for informations like this:

// Tuesday
array[2][1] = "tuesday";
array[2][2] = "20:00";

// Wednesday 
array[3][1] = "Wednesday";
array[3][2] = "15:00";

// Thursday 
array[4][1] = "Thursday";
array[4][2] = "20:00";

// Friday
array[5][1] = "Friday";
array[5][2] = "18:00";

// Saturday
array[6][1] = "Saturday";
array[6][2] = "15:00";

// Sunday
array[7][1] = "Sunday";
array[7][2] = "15:00";

How can I sort the Array by actually Time AND Weekday? Example: Now it's Wednesday - 11:13. The first Array-Item will be the array[3], then 4,5,6,7 and then again 2.

Thank you very much.

like image 859
user1878413 Avatar asked Aug 06 '26 17:08

user1878413


1 Answers

You should use Arrays.sort(array,comparator), e.g. something like this:

Arrays.sort(array, new Comparator<String[]>() {
    public int compareTo(String[] one, String[] two) {
         // implement compareTo here
    }
});

But it is very bad practice to use 2 dimensional array for different data instead of 1 dimensional array of custom type, i.e.:

public class DayTime {
    private String day;
    private String time;
    // constructors, setters, getters
}

Now create array like this:

DayTime[] days = new DayTime[] {
    new DayTime("tuesday", "20:00").
    new DayTime("Wednesday", "15:00"),
    // etc, etc
};


Arrays.sort(array, new Comparator<DayTime>() {
    public int compareTo(DayTime one, DayTime two) {
         // implement compareTo here
    }
});

You can also make DateTime to implement Comparable. In this case just call Arrays.sort(array)

like image 105
AlexR Avatar answered Aug 08 '26 13:08

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!