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?
In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.
This example demonstrate about How to sort an array elements in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
For sorting the list with the property, we use list 's sortedWith() method. The sortedWith() method takes a comparator compareBy that compares customProperty of each object and sorts it. The sorted list is then stored in the variable sortedList .
We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.
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());
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); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With