Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Sorting an ArrayList by date

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 354
    Comment on it

    From here you can learn how to sort an Array List of a particular data type by one it date component. :-

    By calling the method below you can easily sort your array list.

    The format you put inside the SimpleDateFormat method is the format of the dateString you are having inside your array.

    public void sortListByDate() 
        {
            Collections.sort(LIST, new Comparator() {
    
            @Override
            public int compare(DataType lhs, DataType rhs) {
                // TODO Auto-generated method stub
    
                String date1 = lhs.getDate1();
                String date2 = rhs.getDate2();
    
                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                Date lhsDate = null,rhsDate = null;
                try {
                    lhsDate = sdf.parse(date1);
                    rhsDate = sdf.parse(date2);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
                if(lhsDate.getTime()>rhsDate.getTime())
                {
                    return 1;
                }
                else if(lhsDate.getTime()<rhsDate.getTime())
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
        });
    }
    

    In the method sortListByStartingDate() the two dateString entering, is converted into simple date format which can read by the android compiler. Then further they are converted into millisecond and finally compared as shown.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: