in my code I have ArrayList<TreeMap<String, Object>>. What TreeMap would have is the key and value. there is a key named sent_date with the value in format of yyyy-MM-DD HH:MM:SS. I can't find a way to sort this list...Can someone please help? thanks.
            Asked
            
        
        
            Active
            
        
            Viewed 622 times
        
    0
            
            
         
    
    
        user1865027
        
- 3,505
- 6
- 33
- 71
- 
                    2How exactly do you want your list sorted? What have you already tried? – PM 77-1 Jun 19 '14 at 23:28
- 
                    Are you saying that each `TreeMap` element contains only 1 entry? Why not just use a `TreeMap` and forgo the `ArrayList` entirely if so? – jpmc26 Jun 19 '14 at 23:29
- 
                    1Would a guava Table be a better data structure? http://docs.guava-libraries.googlecode.com/git-history/v17.0/javadoc/com/google/common/collect/Table.html – Brett Okken Jun 19 '14 at 23:36
- 
                    1`TreeMap` has more entries, and sent_date is one of them. – user1865027 Jun 20 '14 at 00:07
- 
                    when I tried to loop through the `ArrayList` and print out the values in the `TreeMap`, I wish to have them in order by sent_date. I was thinking this can be done right after elements are all added to the `ArrayList` so I don't have to change my loop – user1865027 Jun 20 '14 at 00:09
- 
                    What is `sent_date`? Is it a class? A variable? – jpmc26 Jun 20 '14 at 01:00
- 
                    Possible duplicate of http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – Raedwald Jun 20 '14 at 04:42
2 Answers
1
            You can use Collections.sort(list, comparator), where you have to implement a Comparator<Map<String,?>> to do what you need (i.e. retrieve the sent_date from two maps and compare those).
 
    
    
        Thilo
        
- 257,207
- 101
- 511
- 656
- 
                    1I'll also +1 anyone who posts a concise implementation with the new Java8 features. This must be possible now without much boilerplate. – Thilo Jun 19 '14 at 23:34
- 
                    comparator is the part I don't get it...Can you please give me more example? – user1865027 Jun 20 '14 at 00:05
1
            
            
        In Java 8, this would be (for a sort that modifies the list):
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
list.sort(Comparator.comparing(m -> LocalDateTime.parse(m.get("sent_date"), format)));
Or if you want to keep the original list:
newList = list.stream()
              .sorted(Comparator.comparing(...))
              .collect(Collectors.toList());
 
    
    
        Mark Peters
        
- 80,126
- 17
- 159
- 190