Android sort arraylist by properties

74,059

Solution 1

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

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

Kotlin code

list.sortWith(Comparator { o1, o2 -> o1.name!!.compareTo(o2.name!!) })
Share:
74,059
Simon
Author by

Simon

I'm a Computer Science and Engineering student at TU Delft in The Netherlands. Also, I work part time as a software engineer.

Updated on April 01, 2021

Comments

  • Simon
    Simon about 3 years

    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?

  • Simon
    Simon almost 12 years
    Thanks, but i still have one problem. I want to sort the arraylist in an activity. At the beginning stands: public class fishList extends ListActivity{ And when I write public class FishNameComparator implements Comparator<String>{ It gives two errors saying: illegal modifier for the local class FishNameComparator; only abstract or final is permitted. And: The type FishNameComparator must implement the inherited abstract method Comparator<String>.compare(String, String). I just did what stands in your answer.
  • K-ballo
    K-ballo almost 12 years
    @user1380611: If you are implementing this as a nested class, then it has to be a static class. And I messed up my example, it should be implements Comparator<Fish>.
  • IgorGanapolsky
    IgorGanapolsky almost 11 years
    Works perfectly for me. Sorts in ascending order here.
  • imike
    imike over 7 years
    This one much better!