Christoph Zahn
Christoph Zahn

Reputation: 25

What is the right way to sort my ArrayList?

I have a custom class called "ergebnisse" with several fields, one of them is score of type Long.

I want to sort an ArrayList<ergebnisse> by score. I tried a lot of things, but most most are fore one or two columns.

ArrayList<ergebnisse> list = new ArrayList<ergebnisse>();
Cursor data = mDatabaseHelper.fetchNamesByConstraint(filter);
while(data.moveToNext()){
    //get the value from the database in column 1
    //then add it to the ArrayList
    String name = data.getString(1);
    String scorestring = data.getString(2);
    Long score=Long.parseLong(scorestring);
    String timestring = data.getString(3);
    Double time= Double.parseDouble(timestring);
    String mode = data.getString(5);
    String game = data.getString(4);
    String levstring = data.getString(6);
    Integer lev=Integer.parseInt(levstring);
    list.add(new ergebnisse(name,score,time,mode,lev,game));
}

I want to sort from highest to lowest score.

Upvotes: 1

Views: 156

Answers (3)

DASH
DASH

Reputation: 132

This can be done in many ways.

Method 1(Traditional):

your custom class

public class Ergebnisse {

    private String name;
    private Long score;

   //standard getters and setters
}

implement comparator interface by overriding compare method

class SortbyScore implements Comparator<Ergebnisse> { 
    @Override
    public int compare(Ergebnisse a, Ergebnisse b) { 
    return b.getScore() - a.getScore(); 
    } 
} 

Then whenever you want list to be sorted by score use

Collections.sort(list, new SortbyScore());

Method 2(Java 8 or above):

Simply use lambda expresson

list.sort((o1, o2) -> o2.getScore().compareTo(o1.getScore()));

*Do note that its important to use wrapper class of primitive type long(Long) to store score variable for this to work!

Upvotes: 0

tomi
tomi

Reputation: 423

For example, if we have a class:

  private class Person{
    private String name;
    private Long score;
  }

Then we can compare like:

list.sort(Comparator.comparing(Person::getScore));

or

list.sort((person1, person2) -> person1.getScore().compareTo(person2.getScore()));

Upvotes: 0

jspcal
jspcal

Reputation: 51904

You can pass a custom comparison function to sort:

Collections.sort(
    list,
    (a, b) -> Integer.compare(b.score, a.score)
);

You'll notice b.score is the first arg to Integer.compare. That reverses the meaning of the comparison so that the list will be in descending order.

Upvotes: 2

Related Questions