javalisttimeminimumdatetime-parsing

How to sort the earliest time stamp in the list in java?


package collectionCollections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.SynchronousQueue;

public class TestCollections {

 public static void main(String[] args) {

  String a = "9:50 PM,12:25 PM,3:55 PM,10:15 PM,1:15 PM";
  ArrayList al2 = new ArrayList();
  ArrayList al3 = new ArrayList();
  String arg[] = a.split(",");
  // System.out.println(arg);
  // Collections.sort(list);
  List < String > al = new ArrayList < String > ();
  al = Arrays.asList(arg);
  for (String s: al) {
   System.out.println(s);
   al2.add(s.substring(0, 5).replace(':', '.'));
  }
  System.out.println(al2);
  Iterator li = al2.iterator();
  while (li.hasNext()) {
   String s = (String) li.next();
   float no = Float.parseFloat(s);
   al3.add(no);
  }
  Collections.sort(al3);
  int add = 0;
  float ff = 0;
  ListIterator lit = al3.listIterator();
  while (lit.hasNext()) {

   float f = (Float) lit.next();
   int intno = (int) f;
   if (intno == 12) {
    add = intno;
    ff = f - add;
    System.out.println(ff);
    lit.remove();
   }
  }
  al3.add(0, add + ff);
  System.out.println(al3);
 }
}

(`I am trying to Sort the below Array list:

my Timestamps = [12:40 PM, 4:00 PM, 7:20 PM, 10:40 PM, 12:00 PM, 3:25 PM, 6:50 PM, 10:15 PM, 6:35 PM, 9:50 PM, 12:20 PM, 3:45 PM, 7:15 PM, 10:40 PM, 11:45 AM, 3:10 PM, 6:35 PM, 10:25 PM, 12:50 PM, 4:10 PM, 7:30 PM, 10:40 PM]

Expected result to display the earliest 11:45 AM in the zeroth index.

I have tried converting above list into integer and when there is unique time (AM/PM)in particular hour(12:35 PM) i was able to sort it but when there are multiple time stamp in particular hour(12:35 PM, 12:05 PM) i am unable to sort.


Solution

  • One of the most simple solution for you is the code below with few changes from yours :

    With the list

    String a = "9:50 PM,12:25 PM,3:55 PM,10:15 PM,1:15 PM,1:00 AM, 12:25 AM, 10:13 AM";
    

    the result is :

    [12:25 AM, 1:0 AM, 10:13 AM, 0:25 PM, 1:14 PM, 3:55 PM, 9:50 PM, 10:14 PM]
    

    A more efficient code is coming in a later edit.