cancel
Showing results for 
Search instead for 
Did you mean: 

Sorting ArrayList

Former Member
0 Kudos

Hello,

I have a ArrayList inside a ArrayList and that inner ArrayList has date field, I want to sort outer array by this date field how can I do that.

Below is the Struction

Outer ArrayList (Need to sort this)
 |
 |______Inner ArrayList
              |
              |_______Date Field

Thanks

Accepted Solutions (1)

Accepted Solutions (1)

0 Kudos

Hi,

I wrote a simple test which I hope will help you....

public class TestDate {

public static void main(String[] args) {

//here i initialize the mentonied by you construction an array with a date filed inside an array

ArrayList list1 = new ArrayList();

for(int i=0;i<10;i++){

Date dt = new Date();

ArrayList list2= new ArrayList(1);

//just to get different values ))

try{

Thread.sleep(iii*i);

}catch(Exception e){

e.printStackTrace();

}

list2.add(dt);

list1.add(list2);

}

// samole output before sorting

for(int i=0;i<10;i++){

System.out.println(list1.get(i));

}

// sorting the array list according to the comparator

Collections.sort(list1, new TestDate().new SortDes());

//result after sorting

System.out.println("after sort");

for(int i=0;i<10;i++){

System.out.println(list1.get(i));

}

}

//Class that sort in descending order

private class SortDes implements Comparator{

public int compare(Object o1, Object o2){

Date m1 = (Date)((ArrayList)o1).get(0);

Date m2 = (Date)((ArrayList)o2).get(0);

if(m1.compareTo(m2)==0)

return 0;

else if (m1.compareTo(m2)>0)

return -1;

else return +1;

}

}

}

Former Member
0 Kudos

Very nice, just don't forget to use the tags !!

public class TestDate {

public static void main(String[] args) {
//here i initialize the mentonied by you construction an array with a date filed inside an array
ArrayList list1 = new ArrayList();
for(int i=0;i<10;i++){
Date dt = new Date();
ArrayList list2= new ArrayList(1);
//just to get different values ))
try{
Thread.sleep(i*i*i*i);
}catch(Exception e){
e.printStackTrace();
}
list2.add(dt);
list1.add(list2);
}
// samole output before sorting
for(int i=0;i<10;i++){
System.out.println(list1.get(i));
}
// sorting the array list according to the comparator
Collections.sort(list1, new TestDate().new SortDes());
//result after sorting
System.out.println("after sort");
for(int i=0;i<10;i++){
System.out.println(list1.get(i));
}
}
//Class that sort in descending order
private class SortDes implements Comparator{
public int compare(Object o1, Object o2){
Date m1 = (Date)((ArrayList)o1).get(0);
Date m2 = (Date)((ArrayList)o2).get(0);
if(m1.compareTo(m2)==0)
return 0;
else if (m1.compareTo(m2)>0)
return -1;
else return +1;
} 
}
}

Edited by: Tulio Vargas on Jul 29, 2010 7:56 PM

Edited by: Tulio Vargas on Jul 29, 2010 7:57 PM

Answers (0)