Reputation: 10209
what I am trying to do is sort the values from a list from greatest to least. i am trying to use Collections.sort(mylist) but i am not sure of what comparator to use to sort them from greatest to least. any suggestions on how to do this?
Upvotes: 3
Views: 38555
Reputation: 649
This is another clean solution.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class Solution {
public static void main(String[] args) {
List<Integer> lst = Arrays.asList(1, 6, 3, 8, 5, 9, 2, 7, 4);
lst.sort(Collections.reverseOrder());
System.out.println(lst);
}
}
Output
[9, 8, 7, 6, 5, 4, 3, 2, 1]
Upvotes: 0
Reputation: 35587
You can do it this way too
Collections.sort(myList);
Collections.reverse(myList);
Edit:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class A {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(5);
myList.add(1);
myList.add(3);
myList.add(2);
myList.add(9);
myList.add(15);
Collections.sort(myList);
Collections.reverse(myList);
System.out.println(myList);
}
}
Upvotes: 7
Reputation: 23797
this is short and sweet:
Integer[] numArray = {1, 2, 3, 4, 5, 0, 9, 8, 7, 6};
List<Integer> numList = new ArrayList<>(Arrays.asList(numArray));
Collections.sort(numList , Collections.reverseOrder());
OUTPUT:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Upvotes: 0
Reputation: 41281
The accepted standard for a comparator for an increasing sort is o1.intValue()-o2.intValue()
We'll simply reverse this:
Comparator ourComparator=new Comparator<Integer>(){
public int compare(Integer o1, Integero2) {
return o2.intValue()-o1.intValue();
}
You can then do as follows:
Collections.sort(ourCollection, ourComparator);
The reverse operation would only apply if your list was already sorted ascending going in, which cannot be guaranteed as you didn't specify your types.
Upvotes: 3
Reputation: 2482
You can use this code to sort by id for example:
public static class SceneComparator implements Comparator<Scene> {
@Override
public int compare(Chair sc, Chair scc) {
return (sc.getId() > scc.getId()) ? -1
: (sc.getId() < scc.getId()) ? 1 : 0;
}
}
List<Scene> scenes = myClass.getScenes();
Collections.sort(scenes, new ScenesComparator());
Hope you find it usefull
Cheers,
Upvotes: 2
Reputation: 272417
You likely need a comparator for your your contained objects, or that your objects implement Comparable. Collections.sort() will then do what you want.
Note also you'll likely result in an ascending result, and you can reverse the result using Collections.reverse(), instead of creating a new comparator.
Npote also the referenced methods sort in place and will affect your original list. You may wish to create a new sorted list (in which case duplicate the list and then sort it)
(I see now you're using Integers, and the above applies wrt. Comparable)
Upvotes: 3