简体   繁体   中英

Sorting Arraylist of Arraylist of Bean

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

ArrayList<ArrayList<DriverLogDatePair>> driverLogList

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

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

But I am not able to sort driverLogList .

You have to complete 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;
   }});

Because the first array contains an array which contains a Comparable. The comparator you provide is for DriverLogDatePair not for ArrayList< DriverLogDatePair >

(... After 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 of the true meaning of this comparison. It's a semantic problem, is this really what you want?

The problem is that if you sort driverLogList it tries to compare the contained ArrayList objects. I would write a wrapper for that 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;

Generally, you can sort List s using

Collections.sort( list , comparator )

So, assuming you want to sort the inner lists, iterate through the outer list and use that construct to sort the elements, after having implemented a fitting comparator:

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

Cheers,

Your compare method is seems wrong to me..

it should be like: (here i am assuming date as DriverLogDatePair Object )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM