Sorting an ArrayList of arrays in java
Sorting an ArrayList of arrays in java
I'd like to know if you know a way to sort an ArrayList of arrays in Java.
I have a function that gives a score between 0 and 1 to a specific array. And I'd like to sort the ArrayList so that arrays having the highest score come first.
public double evaluate(int toEvaluate) {
double result = 0.0;
for (int i = 0; i < toEvaluate.length; i++) {
result += table[i][casesMap.get(toEvaluate[i])];
}
return result / toEvaluate.length;
}
Any ideas ?
4 Answers
4
You should use Collections.sort()
together with a custom Comparator
:
Collections.sort()
Comparator
List<Integer> arrays = new ArrayList<>();
arrays.add(new Integer{1, 2});
arrays.add(new Integer{3, 4});
Collections.sort(arrays, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return 1; // FIX this according to your needs
}
});
compare()
above is just a stub, you should implement it according to the documentation and it could be replaced with a lambda expression. In the code above that would be: Collections.sort(arrays, (a, b) -> 1)
.
compare()
Collections.sort(arrays, (a, b) -> 1)
You have to write a Comparator and compare method override where you can use your function to calculate comp value
@Override
public int compare(Integer o1, Integer o2) {
int o1Number=ratingFunction(o1) ;
int o2Number=ratingFunction(o2) ;
int cmp=o1Number.compareTo(o2Number);
return cmp;
}
You can either use comparator to sort list in descending order or you can use Collections sort method and then use reverse method to make it descending order,
something like this :
List<Integer> numberList =new ArrayList<Integer>();
numberList.add(3);
numberList.add(1);
numberList.add(2);
//before sort
for (Integer integer : numberList) {
System.out.println(integer);
}
//sorting
Collections.sort(numberList);
Collections.reverse(numberList);
//after sort
for (Integer integer : numberList) {
System.out.println(integer);
}
You might want to use stream
api for that. So let's say we have the scoring function (I simplified it for the sake of example).
stream
public static double evaluate(int arr){
return Arrays.stream(arr).sum() / arr.length;
}
Now we can use it with Comparator.comparing
method:
Comparator.comparing
List<int> list = Arrays.asList(new int{4, 5},
new int{2, 3}, new int{0, 1});
List<int> sorted = list.stream().
sorted(Comparator.comparing(Main::evaluate)).
collect(Collectors.toList());
sorted.forEach(x -> System.out.println(Arrays.toString(x)));
The idea behind the code is quite simple, you provide a comparator which defines how to sort int
arrays. I hope this helps.
int
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Google for Comparator.
– GhostCat
May 24 '17 at 10:48