Java sort list containing list by list index value?

I have a nested list as shown below (but it contains 1000 lists holderin one main list). Let's say I need to sort the main list listEmailDataby value for each of its lists holderin the index holder.get(2). It seems I can’t 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 in which each list entry contains a sub-list, in 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 in each sub-list.

2ND EDIT: Thanks for helping me with this, it made it work, but it seems that it puts large numbers ahead and large numbers later, I was hoping to reverse this, so it goes from the largest to the smallest like me.

+3
source share
1 answer

You must implement Comparator<T>to compare lists and then call

Collections.sort(listEmailData, comparator);

Your comparator will need to compare any two "sublists" - for example, by getting a specific value. For instance:

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);
    }
}

Please note that this uses generics - hope your real code too.

+6
source

All Articles