Sort Arraylist Arraylist Bean

I have an ArrayList from an ArrayList from a Bean, and I need to sort this ArrayList according to the date variable in the Bean.

 ArrayList<ArrayList<DriverLogDatePair>> driverLogList 

And the DriverLogDatePair Bean have a DateTime date variable, it also has a compareTo method.

 public int compareTo(DriverLogDatePair o) { return date.compareTo(o.date); } 

But I can not sort driverLogList .

+1
source share
4 answers

You must fill out this code:

 ArrayList<ArrayList<DriverLogDatePair>> driverLogList = new ArrayList<>(); Collections.sort( driverLogList, new Comparator<ArrayList<DriverLogDatePair>>(){ @Override public int compare( ArrayList<DriverLogDatePair> left, ArrayList<DriverLogDatePair> right ) { return 0; }}); 

Since the first array contains an array that contains Comparable. The comparator you provide is for DriverLogDatePair not for ArrayList <DriverLogDatePair>

(... after the comments of this post ...)

At your request, to complete the comparator, I suggest:

 int size = left.size(); int diff = size - right.size(); if( diff != 0 ) return diff; for( int i = 0; i < size; ++i ) { diff = left.get( i ).compareTo( right.get(i) ); if( diff != 0 ) return diff; } 

But I have no idea about the true meaning of this comparison. This is a semantic problem, is it really what you want?

+3
source

The problem is that if you sort driverLogList , it tries to compare the contained ArrayList objects. I would write a wrapper for this list:

 public class DriverLogDatePairList extends ArrayList<DriverLogDatePair> implements Comparable<DriverLogDatePairList> { public int compareTo(DriverLogDatePairList o) { //your comparison criteria } } 

Then you can use it this way and sort it:

 ArrayList<DriverLogDatePairList> driverLogList; 
0
source

Generally, you can sort the List with

 Collections.sort( list , comparator ) 

So, assuming you want to sort the internal lists, iterate over the external list, and use this construct to sort the elements after the fitting mapping is implemented:

 Comparator comparator = new Comparator<DateTime>() { @Override public int compare( DateTime o1, DateTime o2 ) { return o1.compareTo( o2 ); } } 

Greetings

0
source

Your comparison method seems wrong to me ..

it should look like this: (here I accept the date as a DriverLogatePair object)

 public int compareTo(DriverLogDatePair o) { if(date.date < o.date) return -1; else if (date.date < o.date) return 0; else return 1; } 
0
source

All Articles