views:

45

answers:

2

I have an arraylist which I need to sort and also I need a specific default item to be on top of the list. I can do that myself checking the array list, delete the default item and insert it at the top of the list. Basically the list should be having a default value on top and remaining values in sorted order.

Wants to know is there any existing api method instead of myself doing all this?

+2  A: 

I'd just write a method that did what you describe... something like:

public static <T> void sortWIthDefault(final List<T> list)
{
    Collections.sort(list);
    // remove the default item
    // insert the default item at the start of the list
}

You could also make use of a comparator (it would be less obvious though) where it always compares the default item as the lowest in any comparison and the natural comparison for the rest of the items. For that you would call Collections.sort(List, Comparator);

Here is some code for such a Comparator... again. I don't really like it because it isn't obvious... but it is a reasonable solution I guess:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main
{
    public static void main(final String[] argv)
    {
        final List<Integer> list;

        list = new ArrayList<Integer>();

        for(int i = 10; i > 0; i--)
        {
            list.add(i);
        }

        Collections.sort(list, new DefaultAtStartComparator<Integer>(5));

        System.out.println(list);
    }
}

class DefaultAtStartComparator<T extends Comparable>
    implements Comparator<T>
{
    private final T defaultValue;

    public DefaultAtStartComparator(final T value)
    {
        defaultValue = value;
    }

    public int compare(final T a,
                       final T b)
    {
        if(a.equals(defaultValue))
        {
            return (-1);
        }

        if(b.equals(defaultValue))
        {
            return (1);
        }

        return (a.compareTo(b));
    }
}
TofuBeer
I would prefer first solution only since second seems a bit odd, we generally expect a comparator to sort only. Thanks TofuBeer.
Reddy
+1  A: 

Not that I'm aware of. You might just need to do something manually like you said...e.g.

List<T>  list = new ArrayList<T>();
//  Insert items into list
...

Collections.sort(list);

T defaultValue = null;
for (int i = 0; i < list.size(); i++) {
    T value = list.get(i);
    if (isDefaultValue(defaultValue)) {           
        defaultValue = list.remove(i);
    }        
}

if (defaultValue != null) {
    list.add(0, defaultValue);
}
digiarnie