How can I order a LinkedList?

1

So as I said in the title I need to sort a LinkedList of an object and these objects as a sort parameter.

Follow the code:

 public LinkedList getOrderOfActivityCompletion() {
        LinkedList<Activity> activityOrder = new LinkedList<>();

        if (!activityList.isEmpty() && !times.isEmpty()) {

            for (Activity a : activityList.values()) {

                activityOrder.add(a);


            }

        } else {
            throw new UnsupportedOperationException("Not supported yet.");
        }
        return activityOrder;

I need to do 2 (two) FOR to order this LinkedList ?

    
asked by anonymous 14.11.2015 / 20:53

2 answers

2

Tom, for this situation of simple ordering, you do not need to implement a whole logic of comparison, java itself already provides apis for ordering lists through the Collections.sort() method, this method offers 2 parameter options, the first one that The following example shows how to do this:

LinkedList<String> lista = new LinkedList<>();
Collections.sort(lista);

If the class does not implement Comparable , then it will be necessary to implement a Comparable , which can be quietly received by Comparator method as an anonymous class:

LinkedList<String> lista = new LinkedList<>();
Collections.sort(lista, new Comparator<String>() {

    @Override
    public int compare(String objetoUm, String objetoDois) {
        // Sua implementação de comparador aqui
        return objetoUm.compareTo(objetoDois);
    }
});

In this code snippet, I'm using the sort implementation of compareTo itself, but you can implement it any way you like.

    
16.11.2015 / 12:06
0

You can implement this directly.

Collections.sort (quotas, (a, b) -> a.getName ()) compareTo (b.getName ())) ;;

    
03.05.2017 / 18:49