I have declared an integer dynamic in Java, that is:
ArrayList<Integer> lista = new ArrayList<Integer>();
... I'm already adding numbers to this one.
lista.add(5); lista.add(7); lista.add(3);
What I want is to order that list, and make it look like this 3, 5, 7
, and for that, I tried to use a method called sort
, as follows.
lista.sort();
But he asks me for an argument that I don't know. I would like to order it from smallest to largest, although if I can sort it from largest to smallest, it doesn't matter, because then I can flip the list.
The error I have is:
The method sort(Comparator<? super Integer>) in the type ArrayList<Integer> is not applicable for the arguments ()
How do I go about applying that sort method to the list?
Before Java 8 you can call the
.sort()
like this:Demonstration .
As of Java 8, you can simplify the call using a lambda expression:
Demonstration .
Or you can also use the answer proposed by @Error404.
You can do it by importing the class
Collections
:And using the method
sort
as follows:So your complete example would be:
Which would give you the following output: