Android sort arraylist by properties
JavaAndroidSortingArraylistJava Problem Overview
I want to sort an ArrayList
by a property. This is my code...
public class FishDB{
public static Object Fish;
public ArrayList<Fish> list = new ArrayList<Fish>();
public class Fish{
String name;
int length;
String LatinName;
//etc.
public Vis (String name) {
this.name = name;
}
}
public FishDB() {
Fish fish;
fish = new Fish("Shark");
fish.length = 200;
fish.LatinName = "Carcharodon Carcharias";
fish = new Fish("Rainbow Trout");
fish.length = 80;
fish.LatinName = "Oncorhynchus Mykiss";
//etc.
}
}
}
Now I want in want to sort this ArrayList
by a property e.g the latinname
in another activity. But I don't know how to do that. Does anybody know how?
Java Solutions
Solution 1 - Java
You need to implement a Comparator
, for instance:
public class FishNameComparator implements Comparator<Fish>
{
public int compare(Fish left, Fish right) {
return left.name.compareTo(right.name);
}
}
and then sort it like this:
Collections.sort(fishes, new FishNameComparator());
Solution 2 - Java
You can simply do it by this code:
Collections.sort(list, new Comparator<Fish>() {
public int compare(Fish o1, Fish o2) {
return o1.name.compareTo(o2.name);
}
});
Solution 3 - Java
Kotlin code
list.sortWith(Comparator { o1, o2 -> o1.name!!.compareTo(o2.name!!) })
Solution 4 - Java
There are multiple options how to achieve the same goal. The easiest solutions would be utilizing Java 8 features:
Collections.sort(Fish, (t1, t2) -> t1.name().compareTo(t2.name()));