3

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.

7
  • 13
    Your code suffers from the Object Denial smell, which will make everything, including your current issue, more difficult to do. Java wants you to write classes, don't resist. Commented May 29, 2013 at 9:21
  • Today is Wednesday - 11:35 german time. 3(today, 15:00), 4 (after wednesday is thursday),5,6,7,2 (because after Sunday is (in this array) tuesday (no monday)). I edit my Question: actually Time AND Week Day. Commented May 29, 2013 at 9:22
  • I would be tempted to say that Arrays are not the best data structure to use for this Commented May 29, 2013 at 9:22
  • Maybe, but what would be the best structure? A Link or a example would be helpfull. Commented May 29, 2013 at 9:23
  • Isn't it posible to change the way you save this information? Couldn't you use for instance Joda Time or XMLGregorianCalendar or your own object? Commented May 29, 2013 at 9:24

5 Answers 5

6

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)

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

Comments

3
class CalendarEntry implements Comparable<CalendarEntry> {
  String entry;
  Date start;

  // constructors, getters, setters

  int compareTo(CalendarEntry o) {
    if (o==null) return 1;
    return start.compareTo(o.start);
  }

}

List<CalendarEntry> entriesList = new ArrayList<CalendarEntry>();
// add contents
Collections.sort(entriesList);
// and you are done

Comments

2

The other Answers here are good, but use outmoded classes.

java.time

With Java 8 and later we now have the java.time framework built-in (with back-ports for Java 6 & 7 and Android). A vast improvement over the old date-time classes.

The java.time classes include a pair of classes that fit your exact needs:

  • DayOfWeek
    A handy enum to represent each of the seven days of the week, as defined by the ISO 8601 standard running from Monday to Sunday.
  • LocalTime
    Represents a time-of-day without date and without time zone.

With these types pre-defined, you do not even need to define your own class as suggested by other comments and answers. At least if your definition of sorting the days runs Monday-Sunday. The DayOfWeek enum has predefined days of the weeks in that order. You could make your own class combining the DayOfWeek and LocalTime if it makes sense your greater project.

Java enums are really handy, flexible, and powerful (so learn more if they are new to you). Enums have their own special implementation of Set and Map, named appropriately, EnumSet and EnumMap. We can use an EnumMap to track each day of the week, mapping it to the time-of-day (a LocalTime object).

EnumMap<DayOfWeek , LocalTime> dayToTimeMap = new EnumMap<> ( DayOfWeek.class );

dayToTimeMap.put ( DayOfWeek.TUESDAY , LocalTime.parse ( "20:00" ) );
dayToTimeMap.put ( DayOfWeek.WEDNESDAY , LocalTime.of ( 15 , 0 ) );
dayToTimeMap.put ( DayOfWeek.THURSDAY , LocalTime.parse ( "20:00" ) );
dayToTimeMap.put ( DayOfWeek.FRIDAY , LocalTime.parse ( "18:00" ) );
dayToTimeMap.put ( DayOfWeek.SATURDAY , LocalTime.parse ( "15:00" ) );

Get the current day-of-week and time-of-day.

DayOfWeek today = DayOfWeek.WEDNESDAY;
LocalTime now = LocalTime.of ( 11 , 13 );

Make a pair of empty sets one to track the day-times that are the same or later than today-now, and one to track the earlier day-times. Being EnumSet, their natural order is the order declared in the DayOfWeek enum (Monday-Sunday, 1-7).

EnumSet<DayOfWeek> earlier = EnumSet.noneOf ( DayOfWeek.class );
EnumSet<DayOfWeek> later = EnumSet.noneOf ( DayOfWeek.class );

Loop the DayOfWeek-to-LocalTime map. See if the DayOfWeek is before, equal to, or later than today. If equal to today, the compare its LocalTime object to our now object. Assign this DayOfWeek object to either the earlier set or the later set.

for ( Map.Entry<DayOfWeek , LocalTime> entry : dayToTimeMap.entrySet () ) {
    DayOfWeek key = entry.getKey ();
    LocalTime value = entry.getValue ();
    int comparison = key.compareTo ( today );
    if ( comparison < 0 ) { // if earlier day…
        earlier.add ( key );
    } else if ( comparison == 0 ) { //If same day…
        if ( value.isBefore ( now ) ) {
            earlier.add ( key );
        } else {  // Else same time as now or later than now…
            later.add ( key );
        }
    } else if ( comparison > 0 ) {
        later.add ( key );
    } else {
        throw new RuntimeException ( "Unexpectedly reached IF-ELSE for comparison: " + comparison );
    }
}

Dump to console. We want to loop the later set first, then the earlier set per the requirements laid out in the Question.

System.out.println ( "dayToStringMap: " + dayToTimeMap );
System.out.println ( "sorted by today: " + today + " " + now + " is: " );
for ( DayOfWeek dayOfWeek : later ) {
    LocalTime localTime = dayToTimeMap.get ( dayOfWeek );
    System.out.println ( dayOfWeek + " " + localTime );
}
for ( DayOfWeek dayOfWeek : earlier ) {
    LocalTime localTime = dayToTimeMap.get ( dayOfWeek );
    System.out.println ( dayOfWeek + " " + localTime );
}

When run.

dayToStringMap: {TUESDAY=20:00, WEDNESDAY=15:00, THURSDAY=20:00, FRIDAY=18:00, SATURDAY=15:00}
sorted by today: WEDNESDAY 11:13 is: 
WEDNESDAY 15:00
THURSDAY 20:00
FRIDAY 18:00
SATURDAY 15:00
TUESDAY 20:00

Comments

1

The sorting itself can be achieved by using Arrays.sort with your own Comparator

http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

public static void main(String[] args) {

  String[][] array = createArray();

  Arrays.sort(array, new Comparator<String[]>() {
    @Override public int compare(String[] o1, String[] o2) {
      String day1 = o1[0];
      String day2 = o2[0];
      String time1 = o1[1];
      String time2 = o2[1];

      // Perform comparison, first of the days, then - if they're
      // identical of the times.
      return ...
    }
  });

}

However, as others have written in the comments: I strongly advise you to take a more object orientated approach to the problem.

Comments

1

Don't use an array here with some "virtual type structure" known to you but not to java. Use strongly-typed class modelling. Implement Comparable for sorting. Then use collections - add object instances to a List and use it's sort method.

 class Event implements Comparable<Event> {
    String day;
    String time;

    public Event(String day, String time) { this.day = day; this.time = time; }
    public String getDay() { return this.day; }
    public String getTime() { return this.time; }

    @Override
    public boolean equals(Object other) {
        boolean result = false;
        if (other != null && other instanceof Event) {
            Event otherEvent = (Event)other;
            result = this.getDay().equals(otherEvent.getDay()) && 
                     this.getTime().equals(otherEvent.getTime());
        }
        return result;
    }

    @Override
    public int hashCode() {
         return this.getDay().hashCode()*7 + this.getDay().hashCode();
    }

    @Override
    public int compareTo(Event otherEvent) {
        int result = this.getDay().compareTo(otherEvent.getDay());
        if (result == 0) result = this.getTime().compareTo(otherEvent.getTime());
        return result;
    }
}

Then in some other class or main method:

List<Event> eventList = new ArrayList<Event>();
eventList.add(new Event("tuesday","20:00"));
eventList.add(new Event("tuesday","20:00"));
// etc

eventList.sort();

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.