Android sort arraylist by properties

JavaAndroidSortingArraylist

Java 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()));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimonView Question on Stackoverflow
Solution 1 - JavaK-balloView Answer on Stackoverflow
Solution 2 - Javaswapnil sahaView Answer on Stackoverflow
Solution 3 - JavaNaimish VinchhiView Answer on Stackoverflow
Solution 4 - JavaNebrass wahaibView Answer on Stackoverflow