How can I order a Linkedlist?

Asked

Viewed 1,154 times

1

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

Follows 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?

2 answers

2

Tomé, for this situation of simple ordering, you do not need to implement a whole comparison logic, java itself already provides Apis for sorting lists through the method Collections.sort(), this method offers 2 parameters options, the first one I demonstrate below, is for situations where your class already implements the interface Comparable:

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

If the class does not implement Comparable, then it will be necessary to implement a Comparator, which can be received smoothly by the method sort 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 piece of code, I am using the implementation of compareTo of own String, but you can implement it the way you prefer.

0

You can implement directly this way.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.