Android-java- How to sort a list of objects by a certain value within the object
Solution 1
You should use Comparable instead of a Comparator if a default sort is what your looking for.
See here, this may be of some help - When should a class be Comparable and/or Comparator?
Try this -
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestSort {
public static void main(String args[]){
ToSort toSort1 = new ToSort(new Float(3), "3");
ToSort toSort2 = new ToSort(new Float(6), "6");
ToSort toSort3 = new ToSort(new Float(9), "9");
ToSort toSort4 = new ToSort(new Float(1), "1");
ToSort toSort5 = new ToSort(new Float(5), "5");
ToSort toSort6 = new ToSort(new Float(0), "0");
ToSort toSort7 = new ToSort(new Float(3), "3");
ToSort toSort8 = new ToSort(new Float(-3), "-3");
List<ToSort> sortList = new ArrayList<ToSort>();
sortList.add(toSort1);
sortList.add(toSort2);
sortList.add(toSort3);
sortList.add(toSort4);
sortList.add(toSort5);
sortList.add(toSort6);
sortList.add(toSort7);
sortList.add(toSort8);
Collections.sort(sortList);
for(ToSort toSort : sortList){
System.out.println(toSort.toString());
}
}
}
public class ToSort implements Comparable<ToSort> {
private Float val;
private String id;
public ToSort(Float val, String id){
this.val = val;
this.id = id;
}
@Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
@Override
public String toString(){
return this.id;
}
}
Solution 2
Follow this code to sort any ArrayList
Collections.sort(myList, new Comparator<EmployeeClass>(){
public int compare(EmployeeClass obj1, EmployeeClass obj2) {
// ## Ascending order
return obj1.firstName.compareToIgnoreCase(obj2.firstName); // To compare string values
// return Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId)); // To compare integer values
// ## Descending order
// return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values
// return Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId)); // To compare integer values
}
});
Solution 3
I think this will help you better
Person p = new Person("Bruce", "Willis");
Person p1 = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas", "Cage");
Person p3 = new Person("John", "Travolta");
ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
}
});
Solution 4
Now no need to Boxing (i.e no need to Creating OBJECT
using new Operator use valueOf insted with compareTo of Collections.Sort..)
1)For Ascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
@Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
}
});
1)For Deascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
@Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
}
});
Solution 5
It's very easy for Kotlin!
listToBeSorted.sortBy { it.distance }
James andresakis
Thanks to those that helped along the way.....
Updated on February 06, 2022Comments
-
James andresakis over 2 years
Im trying to sort through an arraylist of objects by a particular value within the object. What would be the best approach to do such a thing. Should I use Collections.sort() with some kind of comparator?
Im trying to sort a list of objects by a float value they hold in one of the variables.
EDIT: This is what I have so far:
public class CustomComparator implements Comparator<Marker> { @Override public int compare(Mark o1, Mark o2) { return o1.getDistance().compareTo(o2.getDistance()); } }
the error states: Cannot invoke compareTo(double) on the primitive type double.
Is it because a comparator cant return anything other than a certain type?
-
James andresakis over 12 yearsBut how do I make it sort by a value within the object. Thats what Im stuck on.
-
James andresakis over 12 yearsI went ahead and implemented Comparable in my class but and created a method to call sort on the list when i need to have it sorted but how do I sort it by a value with in the object?
-
Jave over 12 yearsThe
compareTo()
-method is where you do the comparison. A little googling gave several detailed examples on how to use it, here is one of them: javadeveloper.co.in/java-example/java-comparable-example.html -
James andresakis over 12 yearsI set up a method similar to the example however I get an error stating I cant use compareTo on a cast double. It seems like for what ever reason, what Im doing it doesnt like. Cannot invoke compareTo(double) on the primitive type double. Ill add my code up above to show what I mean
-
James andresakis over 12 yearsHey thanks for the link :) I go back and forth from one language to the next so Im always missing something :p you know how it goes......jack of all trades but a master of none lol
-
John Smith about 9 yearsThis should be the top answer!
-
Sadashiv over 8 yearssimple & great answer, kudos bro:)
-
Ambran over 7 yearsThis example works for comparing strings. For sorting by comparing integers look at Pranav's answer below.
-
Meet Vora over 7 yearsSimple and small.. Thanks!
-
Anurag over 7 yearsThis seems really clean. thanks. And One plus for provided tips.
-
Sohail Yasin about 7 yearsBest and simple answer. saved my time
-
Innocent over 6 yearsgreat answers are always from great people, thank you so much you
-
Vaclovas Rekašius Jr. over 6 yearsThis should really be the real answer, quick, simple, clear. Thanks.
-
Atif Mahmood almost 5 years@Themelis it's java function
-
Ali Zarei over 4 yearsint compare can be replaced by: return Integer.compare(obj1.empId, obj2.empId);
-
tenTen over 3 yearsPerfectly Working! Thanks bro
-
toto_tata over 3 yearsStackoverflow should add a 'donate' button next to such wonderful answers :)
-
User about 3 yearsthis places names starting from numbers (i.e 1gbfilename) on bottom. how they can be placed at top?
-
Snigdhajyoti over 2 yearssame answer is already given. You can also see different different approaches too.