简体   繁体   中英

Sort string array in java with 3rd element

I have 3 strings . Each string has a time in the string . for example, 1) "1 09:53 AM 5" 2) "2 06:25 PM 7" 3) "3 10:21 AM "

I want these strings sorted according to the time. How can it be done in JAVA?

1st- Parse each line and do this: (Don't forget to remove the first number with StringTokenizer)

String str = "10:20 AM";
SimpleDateFormat formatador = new SimpleDateFormat("hh:mm a");
Date data = formatador.parse(str);
Time time = new Time(data.getTime());

2nd - Save each Time object on the array list declared like this:

ArrayList<Time> list;

3rd - Sort the array

Collections.sort(list);
    List<String> unsorted = Arrays.asList(
            "1 09:53 AM 5",
            "2 06:25 PM 7",
            "3 10:21 AM "
    );
    List<String> sorted = unsorted.stream()
            .sorted(comparing(this::stringToTime))
            .collect(toList());
    sorted.forEach(System.out::println);

This requires the method stringToTime with a couple of supporting constants as follows:

// Used to parse the time string to a LocalTime
private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
        .appendPattern("hh:mm a")
        .toFormatter(Locale.ENGLISH);

// Regex pattern that picks out the time string
private final static Pattern TIME_PATTERN = Pattern.compile("\\d\\d:\\d\\d [AP]M");

private LocalTime stringToTime(String input) {
    Matcher matcher = TIME_PATTERN.matcher(input);
    matcher.find(); // Find time pattern in string
    return LocalTime.from(TIME_FORMATTER.parse(matcher.group())); // Convert time string to LocalTime
}

There is no "out of box" solution in Java. If you need to sort a collection of objects in a custom way, you should use Collections.sort(collection, myComparator) method and pass it the collection to sort and own java.util.Comparator interface implementation.

In your case, the Comparator implementation seems to be quite complicated, since you need to parse each string and recognize the date at first. So the main problem here is how to recognize time in a string . If you have determined time format, consider regular expressions to extract time from strings.

First of all, you need to implement your own time recognition logic. Then you can write a parser based on this recognition logic, that would return you a wrapper object containing original string and parsed date (you can use java.util.Date or java.util.LocalDateTime in case of Java 8). Then implement the Comparator that takes 2 instances of the wrapper object and compares their dates. Both java.util.Date and java.util.LocalDateTime classes implement Comparable interface and have default comparison logic, that uses ascending date comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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