简体   繁体   English

Java - 按时间排序数组

[英]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. 示例:现在是星期三 - 11:13。 The first Array-Item will be the array[3], then 4,5,6,7 and then again 2. 第一个Array-Item将是数组[3],然后是4,5,6,7,然后是2。

Thank you very much. 非常感谢你。

You should use Arrays.sort(array,comparator) , eg something like this: 你应该使用Arrays.sort(array,comparator) ,例如:

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, ie: 但是对于不同的数据使用二维数组而不是自定义类型的一维数组是非常糟糕的做法,即:

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 . 您还可以使DateTime实现Comparable In this case just call Arrays.sort(array) 在这种情况下,只需调用Arrays.sort(array)

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

The other Answers here are good, but use outmoded classes. 这里的其他答案很好,但使用过时的类。

java.time 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). 在Java 8及更高版本中,我们现在内置了java.time框架(带有Java 6&7和Android的后端口)。 A vast improvement over the old date-time classes. 与旧的日期时间类相比有了很大的改进。

The java.time classes include a pair of classes that fit your exact needs: java.time类包含一对符合您确切需求的类:

  • 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. 一个方便的枚举代表每周七天的每一天,由星期一到星期日的ISO 8601标准定义。
  • 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. DayOfWeek枚举按此顺序预定了几周的天数。 You could make your own class combining the DayOfWeek and LocalTime if it makes sense your greater project. 可以让自己的等级组合的DayOfWeekLocalTime ,如果它使你的感觉更多的项目。

Java enums are really handy, flexible, and powerful (so learn more if they are new to you). Java枚举 非常方便,灵活且功能强大(如果对您不熟悉 ,请了解更多内容)。 Enums have their own special implementation of Set and Map , named appropriately, EnumSet and EnumMap . 枚举有自己特殊的SetMap ,适当命名, EnumSetEnumMap We can use an EnumMap to track each day of the week, mapping it to the time-of-day (a LocalTime object). 我们可以使用EnumMap跟踪一周中的每一天,将其映射到时间( LocalTime对象)。

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枚举(周一至周日,1-7)中声明的顺序。

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

Loop the DayOfWeek-to-LocalTime map. 循环DayOfWeek到LocalTime地图。 See if the DayOfWeek is before, equal to, or later than today. 查看DayOfWeek是否在今天之前,等于或晚于今天。 If equal to today, the compare its LocalTime object to our now object. 如果等于今天,则将其LocalTime对象与我们now对象进行比较。 Assign this DayOfWeek object to either the earlier set or the later set. 将此DayOfWeek对象分配给earlier集或later集。

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. 我们希望首先循环later集合,然后根据问题中列出的要求循环earlier集合。

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

The sorting itself can be achieved by using Arrays.sort with your own Comparator 排序本身可以通过使用Arrays.sort和您自己的Comparator来实现

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

http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.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. 但是,正如其他人在评论中写道:我强烈建议您采取更加面向对象的方法来解决问题。

Don't use an array here with some "virtual type structure" known to you but not to java. 不要在这里使用一些已知的“虚拟类型结构”,而不是java。 Use strongly-typed class modelling. 使用强类型类建模。 Implement Comparable for sorting. 实现Comparable进行排序。 Then use collections - add object instances to a List and use it's sort method. 然后使用集合 - 将对象实例添加到List并使用它的sort方法。

 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM