Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android sort arraylist by properties

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?

like image 677
Simon Avatar asked Jun 01 '12 15:06

Simon


People also ask

How can you sort an ArrayList of objects?

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.

How do I sort an array in Android?

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.

How do I sort an ArrayList in Kotlin?

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 .

How do you sort elements in an ArrayList using comparable interface?

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.


2 Answers

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()); 
like image 115
K-ballo Avatar answered Oct 12 '22 06:10

K-ballo


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);     } }); 
like image 24
swapnil saha Avatar answered Oct 12 '22 06:10

swapnil saha