3

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

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

14 Comments

sorry if I'm missing something obvious but I am not quite sure how to make this compare the thousands of entries in a list and then sort the list accordingly, I can see that calling compare() would sort between 2 of the list inputs
@Rick: The comparator compares any two lists. You use Collections.sort on the list of lists using this comparator, as per the first part of the answer.
@Rick - You would not call compare() directly, that is handled by Collections.sort(listEmailData, new ListComparator()) for you.
ok thanks, I think the c in Collections needs to be capitalized, I'm fairly ignorant of collections in Java so that threw me off at first I think as I thought it was a regular variable object name
@Rick: Sorry, yes, that was a typo. Oops.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.