15

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.

12
  • How are you adding points to the team? In the code you included the team objects are placed directly into the list, you show no separate references to them. Commented Jan 23, 2013 at 8:50
  • Check this link:stackoverflow.com/questions/2784514/… Commented Jan 23, 2013 at 8:50
  • @Perception no seperate references to team objects are needed because he has reference to list object and can easily identify team object based on its name. Commented Jan 23, 2013 at 8:52
  • stackoverflow.com/a/14475630/922198 Commented Jan 23, 2013 at 8:52
  • @Subin - sorry, but that's a huge assumption Commented Jan 23, 2013 at 8:53

3 Answers 3

30

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


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

Sign up to request clarification or add additional context in comments.

3 Comments

To solve the comparison problem you can just use Integer.compare()
That's basically what the OP did!? Except he did not create an anonymous class
Right at moment i need it. +1
13
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

Comments

0

It is not actually necessary to define a custom Comparator like this.

Instead, you can easily define one, when you want to sort your ArrayList.

Since JAVA 8 using lamda

    // Sort version.
    Iteams.sort(Comparator.comparing(Team::getPoints));

    // Complete version.
    Iteams.sort((o1, o2) -> o1.getPoints().compareTo(o2.getPoints()));


Also there are options for second comparator, if objects are equals on the first:

    // e.g. if same points, then compare their names.
    Iteams.sort(Comparator.comparing(Team::getPoints).thenComparing(Team::getName));


Also note that the default sort option is ascending, but you can set it to descending using:

    // e.g. Sort by points descending.
    Iteams.sort(Comparator.comparing(Team::getPoints).reversed());


That way, you can sort your ArrayList in different ways whenever you want, just by adding the method you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.