I have a nested list like below (but it has 1,000's of the holder
lists within the one main list). Say I need to sort the main list listEmailData
by the value for each of its holder
lists on the holder.get(2)
index. I can't seem to figure out开发者_开发百科 how to do this any advice is appreciated.
ArrayList listEmailData;
ArrayList holder = new ArrayList();
listEmailData.add(3)
listEmailData.add(323)
listEmailData.add(2342)
listEmailData.add(holder)
EDIT: To clarify, I have a list where each list entry contains a sub-list, within this sub-list a specific index contains a value that is a ranking. I need to sort the main list based on this ranking value within each sub-list.
2ND EDIT: Thanks for the help on this, got it working but its seems that its putting larger numbers first and large numbers later, I was hoping to reverse this so it goes from largest to smallest as I am
You should implement Comparator<T>
to compare lists, then call
Collections.sort(listEmailData, comparator);
Your comparator would have to compare any two "sublists" - e.g. by fetching a particular value. For example:
public class ListComparator implements Comparator<List<Integer>>
{
private final int indexToCompare;
public ListComparator(int indexToCompare)
{
this.indexToCompare = indexToCompare;
}
public int compare(List<Integer> first, List<Integer> second)
{
// TODO: null checking
Integer firstValue = first.get(indexToCompare);
Integer secondValue = second.get(indexToCompare);
return firstValue.compareTo(secondValue);
}
}
Note that this is using generics - hopefully your real code is too.
精彩评论