sorting a List containing Object[] elements
Problem Statement: How can we sort
a List containing Object[] elements?
The Solution:
Ever wondered how to sort a list full of Object[]? The answer is
to use a Comparator I have used an anonymous class which implements compare
method to sort the List of Object[]
package example.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sorting {
public static void main(String[]
args) {
List<Object[]>
list = new ArrayList<Object[]>();
list.add(new Object[]{123, "abc", 212});
list.add(new Object[]{423, "qwert", 2131});
list.add(new Object[]{656, "asda", 45});
list.add(new Object[]{111, "zxcz", 43});
list.add(new Object[]{10, "poiu", 890});
Collections.sort(list, new Comparator<Object[]>()
{
//Used
by Collections.sort method to sort the List
@Override
public int compare(Object[]
o1, Object[] o2) {
Integer
accId1 = (Integer)o1[0];
Integer
accId2 = (Integer)o2[0];
if(accId1
< accId2)
return -1;
if(accId1
> accId2)
return 1;
return 0;
}
});
for(Object[]
obj : list){
System.out.println("id=
"+obj[0]+", name= "+obj[1]+",
val= "+obj[2]);
}
}
}
Comments
Post a Comment