简体   繁体   中英

Sorting an ArrayList?

I am trying to make a function, that allows you to sort the dates in descending or ascending order. However, I'm not too sure how I should go about this. This is what I've worked out so far, but got completely stuck:

public void sortByYear() {
   String askID = JOptionPane.showInputDialog(null, "Would you like to sort by ascending or descending?");
   if(askID.equalsIgnoreCase("ascending")){
      for(String datePersons : personList){
         String[] splitPerson = datePersons.split("_");
         String date = splitPerson[5];   
      }
   } else if(askID.equalsIgnoreCase("descending")){

     }
}

The format that my ArrayList works with, is this: ID_NAME_MAIL_PHONE_CITY_DATETIME#

Which in the ArrayList , with data in it, looks like this:

7_Geoffrey Wolf_fermentum.risus@malesuadaaugue.net_1-382-295-5799_Warwick_2010-03-27 09:47:41

If I got 99 different persons with different dates, how would I be able to sort them? I used this part to split and find the dates:

String[] splitPerson = datePersons.split("_");
String date = splitPerson[5];

Best Regards.

Use the Arrays.sort method and use a custom comparator. In the comparator implementation, parse the date string, construct date object and compare them.

ie

Arrays.sort(personList, new Comparator<String>() {
   public int compare(String person1, String person2) {
       Date date1 = parseDate(person1);
       Date date2 = parseDate(person2);
       return date1.compareTo(date2);
       //return date2.compareTo(date1) for reverse order
   } 
});

If personList is a List/Collection and not an array, use sort method in Collections class which works similar to the Arrays.sort method.

First, parse the date string into a proper java.util.Date object using eg a java.text.SimpleDateFormat (assuming your dates are consistently formatted). Then you can sort the list of Date using either the natural ordering or the reverse ordering, depending on the value of askID .

Note that there is no need to write a custom comparator since a reverse comparator comes out of the box: java.util.Collections.reverseOrder() . The following is an example snippet:

public static void sortByYear() throws ParseException {
    // ...
    DateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    List<Date> dateList = new ArrayList<>();
    for (String date : personList) {
        Date parsedDate = format.parse(date);
        dateList.add(parsedDate);
    }
    if (askID.equalsIgnoreCase("ascending")) {
        Collections.sort(dateList);
    } else {
        Collections.sort(dateList, Collections.reverseOrder());
    }
}

The object-oriented solution to the problem would be to create a model class, Person , for holding the different attributes that are currently concatenated into a single string. You could then have Person implement the Comparable interface, eg like this:

public class Person implements Comparable<Person>{

    private Date dateTime;

    /*
    * Clip other fields, constructor and accessor methods.
    */

    @Override
    public int compareTo(Person other) {
        return this.dateTime.compareTo(other.dateTime);
    }
}

Now that the ordering of a Person would be defined based on the dateTime attribute, sorting a List<Person> myPersonList in ascending datetime order is as simple as Collections.sort(myPersonList) and sorting by descending order as simple as Collections.sort(myPersonList, Collections.reverseOrder()) .

Alternatively, the quick-and-dirty solution to the problem is to create a custom Comparator , which would allow you to order a list of List<String> myStringList based on the datetime token (in index 5 , when split by the _ delimiter) of each element:

public class UserInfoDateTimeComparator implements Comparator<String> {

    // see docs for correct format:
    // https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
    private static final DateFormat DATETIME_FORMAT = new SimpleDateFormat(...)

    @Override
    public int compare(String s1, String s2) {

        // guards for null parameters
        if (s1 == null) {
            return s2 == null ? 0 : -1;
        } else if (s2 == null) {
            return 1;
        }

        try {
            Date dateTime1 = DATETIME_FORMAT.parse(s1.split("_")[5]);
            Date dateTime2 = DATETIME_FORMAT.parse(s2.split("_")[5]);
            return dateTime1.compareTo(dateTime2);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

With Comparator<String> myComparator = new UserInfoDateTimeComparator() , myStringList can be sorted through Collections.sort(myStringList, myComparator) in ascending datetime order and through Collections.sort(myStringList, Collections.reverseOrder(myComparator)) in descending order.

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