Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

android - Sort ArrayList with times in Java

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...