Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Arraylist of objects

I have ArrayList, which containst football teams (class Team). Teams have points and i want to sort them by number of points.

 public class Team {
     private int points;
     private String name;

     public Team(String n)
     {
         name = n;
     }

     public int getPoints
     {
         return points;
     }

     public void addPoints(boolean win)
 {
            if (win==true)
            {
    points = points + 3;
            }

            else if (win==false)
            {
            points = points + 1;
            }

}
 //...
 }

Main Class:

 List<Team> lteams = new ArrayList<Team>;

 lteams.add(new Team("FC Barcelona"));
 lteams.add(new Team("Arsenal FC"));
 lteams.add(new Team("Chelsea"));

 //then adding 3 points to Chelsea and 1 point to Arsenal

 lteams.get(2).addPoints(true);
 lteams.get(1).addPoints(false);

 //And want sort teams by points (first index with most points). 

I did my comparator.

 public class MyComparator implements Comparator<Team> {


    @Override
    public int compare(Team o1, Team o2) {
        if (o1.getPoints() > o2.getPoints())
         {
             return 1;
         }
        else if (o1.getPoints() < o2.getPoints())
        {
            return -1;
        }
        return 0;    
    } 

}

now I wanna use it (in main class)

 Colections.sort(lteams, new MyComparator());

I want to see:

  1. Chelsea
  2. Arsenal
  3. Barcelona

But it doesn't sort.

like image 598
n0hepe Avatar asked Jan 23 '13 08:01

n0hepe


People also ask

How do you sort an object in an ArrayList?

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 you sort an ArrayList of objects in Java 8?

– Use Collections. sort() method for sorting the ArrayList in-place, or Java 8 Stream. sorted() to return a new sorted ArrayList of Objects (the original List will not be modified). – For Descending order, just pass Collections.

How do you sort a list containing objects?

sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.

How do you sort collections of objects?

Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.


2 Answers

Source : Here

You can use Collections.sort with a custom Comparator<Team>.

    class Team {
        public final int points;
        // ...
    };

    List<Team> players = // ...

    Collections.sort(players, new Comparator<Team>() {
        @Override public int compare(Team p1, Team p2) {
            return p1.points- p2.points;
        }

    });

Alternatively, you can make Team implementsComparable<Team>. This defines the natural ordering for all Team objects. Using a Comparator is more flexible in that different implementations can order by name, age, etc.

See also

  • Java: What is the difference between implementing Comparable and Comparator?

For completeness, I should caution that the return o1.f - o2.f comparison-by-subtraction shortcut must be used with extreme caution due to possible overflows (read: Effective Java 2nd Edition: Item 12: Consider implementing Comparable). Presumably hockey isn't a sport where a player can score goals in the amount that would cause problems =)

See also

  • Java Integer: what is faster comparison or subtraction?
like image 78
Parimal Raj Avatar answered Sep 19 '22 18:09

Parimal Raj


public class Team {
   private int points;
   private String name;

public Team(String n, int p) {
    name = n;
    points = p;
}

public int getPoints() {
    return points;
}

public String getName() {
    return name;
}

public static void main(String[] args) {
    List<Team> lteams = new ArrayList<Team>();

    lteams.add(new Team("FC Barcelona", 0));
    lteams.add(new Team("Arsenal FC", 2));
    lteams.add(new Team("Chelsea", 3));

    Collections.sort(lteams, new MyComparator());

    for (Team lteam : lteams) {
        System.out.println(lteam.name + ": " + lteam.points + " points");
    }
}

}

class MyComparator implements Comparator<Team> {
@Override
public int compare(Team o1, Team o2) {
    if (o1.getPoints() > o2.getPoints()) {
        return -1;
    } else if (o1.getPoints() < o2.getPoints()) {
        return 1;
    }
    return 0;
}}

Output:
Chelsea: 3 points
Arsenal FC: 2 points
FC Barcelona: 0 points

like image 36
Dmitry Stril Avatar answered Sep 16 '22 18:09

Dmitry Stril