on 07-28-2010 12:01 PM
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
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;
}
}
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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
User | Count |
---|---|
85 | |
10 | |
10 | |
10 | |
7 | |
6 | |
6 | |
5 | |
4 | |
4 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.