AndroidGuy007 AndroidGuy007 - 1 month ago 17
Android Question

Sorting List ascending and descending android java

I have a

List<>
containing data. How can I sort it to ascending and descending?

List<Data> data = new ArrayList<>();

data.add(new Data("Batman vs Superman", "Following the destruction of Metropolis, Batman embarks on a personal vendetta against Superman ", R.drawable.ic_action_movie));
data.add(new Data("X-Men: Apocalypse", "X-Men: Apocalypse is an upcoming American superhero film based on the X-Men characters that appear in Marvel Comics ", R.drawable.ic_action_movie));
data.add(new Data("Captain America: Civil War", "A feud between Captain America and Iron Man leaves the Avengers in turmoil. ", R.drawable.ic_action_movie));
data.add(new Data("Kung Fu Panda 3", "After reuniting with his long-lost father, Po must train a village of pandas", R.drawable.ic_action_movie));
data.add(new Data("Warcraft", "Fleeing their dying home to colonize another, fearsome orc warriors invade the peaceful realm of Azeroth. ", R.drawable.ic_action_movie));
data.add(new Data("Alice in Wonderland", "Alice in Wonderland: Through the Looking Glass ", R.drawable.ic_action_movie));


this is my data class

public class Data {
public String title;
public String description;
public int imageId;

Data(String title, String description, int imageId) {
this.title = title;
this.description = description;
this.imageId = imageId;
}

}

Answer

Let your class implement the Comparable interface, this lets Java handle most of the heavy lifting.

public class Data implements Comparable<Data>{
    @Override
    public int compareTo(Data another) {
        return this.title.compareTo(another.title);
        // can also compareToIgnoreCase if not case sensitive
    }
}

Then simply call Collections.sort(data);

This will sort your data based on the compareTo function in your Data class.

Comments