3

I have a List<String> that contains a list of times from 8:00 am to 4:00 pm.

When I show it in output it appears unsorted, and when I use Collections.sort(myList); it sorts it as from 1:00 pm to 8:00 am.

How could I sort my list from 8:00am to 4:00pm ?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Emy Alsabbagh
  • 287
  • 1
  • 3
  • 8
  • Use 24 hour time format in your list and then sort it. You can revert it back to AM and PM anytime. – Rohit5k2 Feb 27 '16 at 16:08

6 Answers6

11

Don't reinvent the wheel, use collection (or Lambdas if java8 is allowed) How??: keep the list as strings, but use an Anonymous comparator, in there, parse the string to dates, compare them and there you have it. here a snippet:

List<String> l = new ArrayList<String>();
l.add("8:00 am");
l.add("8:32 am");
l.add("8:10 am");
l.add("1:00 pm");
l.add("3:00 pm");
l.add("2:00 pm");
Collections.sort(l, new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
        try {
            return new SimpleDateFormat("hh:mm a").parse(o1).compareTo(new SimpleDateFormat("hh:mm a").parse(o2));
        } catch (ParseException e) {
            return 0;
        }
        }
    });
    System.out.println(l);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
2

Convert your Strings to Dates and sort the dates. In Java in general you should always handle the objects as they are, not Strings. Strings are names or other texts, when there is a special meaning of a String you better convert into that meaningful object.

Henning Luther
  • 2,067
  • 15
  • 22
1

Here is a short program for what you want to do.

public static void main(String[] args) throws ParseException {
    ArrayList<String> times = new ArrayList<String>();
    times.add("8:00 pm");
    times.add("8:00 am");
    times.add("7:00 pm");
    times.add("7:00 am");
    ArrayList<Date> dates = new ArrayList<Date>();
    DateFormat format = new SimpleDateFormat("h:m a", Locale.ENGLISH);
    for(String time : times){
        dates.add(format.parse(time));
    }
    Collections.sort(dates);
    System.out.println(dates);
}

Steps:

  • Convert each string to a standardized Date
  • Sort using Collections.sort()
Atri
  • 5,511
  • 5
  • 30
  • 40
1

DetailsVOTemp model has time and add set-get method and I already have a list which is list with name of list.

Get the time and latlong from the list and store in two arraylist than finally sort it

    List< DetailsVOTemp> firstlist = new ArrayList<>();
    List<DetailsVOTemp> secondlisr = new ArrayList<>();

    for (int i = 0; i < list.size(); i++) {
         DetailsVOTemp mDetailsVOTemp = new  DetailsVOTemp();
        mDetailsVOTemp.setTime(list.get(i).getTime());
        mDetailsVOTemp.setAdd(list.get(i).getLatLong());
        mVoTemps.add(mDetailsVOTemp);
    }
    for (int i = 0; i < list.size(); i++) {
        DetailsVOTemp mDetailsVOTemp = new  DetailsVOTemp();
        mDetailsVOTemp.setTime(list.get(i).getDropOffTime());
        mDetailsVOTemp.setAdd(list.get(i).getDropLatLong());
        mVoTemps1.add(mDetailsVOTemp);
    }

    mVoTemps.addAll(mVoTemps1);
    Collections.sort(mVoTemps, new Comparator<DetailsVOTemp>() {

        @Override
        public int compare(DetailsVOTemp o1, DetailsVOTemp o2) {
            return o1.getTime().compareTo(o2.getTime());
        }
    });

    StringBuilder mBuilder = new StringBuilder();
    StringBuilder mBuilder1 = new StringBuilder();
    for (int i = 0; i < mVoTemps.size(); i++) {
        mBuilder1.append(mVoTemps.get(i).getTime() +" :: ");
        mBuilder.append(mVoTemps.get(i).getAdd() +" :: ");
    }

    Log.d("Time : ", mBuilder1.toString());
    Log.d("Address : ", mBuilder.toString());
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shaikh Mohib
  • 278
  • 3
  • 11
0

Use 24 hour time format in your list and then sort it.

You can revert it back to AM and PM anytime.

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
0

Like others I recommend not reinventing the wheel, and I also recommend discarding the old and outdated classes SimpleDateFormat and Date. We have so much better these days.

Given

static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);

we can do

    Collections.sort(listOfTimeStrings, 
                     Comparator.comparing(
                             (String s) -> LocalTime.parse(s.toUpperCase(), dtf)));

This will work nicely for a few hundred strings, maybe more. It will, however, parse each string each time two strings are to be compared. That could be many times. If you want to parse each string only once, instead do:

    List<String> sortedList = listOfTimeStrings.stream()
            .map(String::toUpperCase)
            .map(s -> LocalTime.parse(s, dtf))
            .sorted()
            .map(dtf::format)
            .map(String::toLowerCase)
            .collect(Collectors.toList());

I have taken it literally when you give am and pm in lowercase, so I am converting to uppercase before the parsing and back to lowercase after formatting. Depending on your data you may skip these steps.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161