Sort ArrayList of Objects by Specific Element

谁说我不能喝 提交于 2019-12-24 00:38:43

问题


I have several arraylists which each contain player data for a specific team. Each object contains the following elements in order; Jersey Number, First Name, Last Name, Preferred Position, Goals, Assists. The user decides whether to view the data by goals or assists, and then the data is displayed in descending order. Goals and assists are both of int data type.

I will be able to display the data fine but what I am stuck on is how to sort the arrayList by one of these specific stats. Because the data from all the teams is in different arrayLists, and need to be sorted all together, do I need to combine the arrayLists into one master arrayList that will be sorted? As for the sorting, I have done a bit of research and it looks like I need to use a comparator? Could someone provide some assistance with this because I have never used these before and am quite lost. Examples would be great.

I have attached a few code snippets to hopefully provide some clarity.

ArrayList <blackTeam> blackTeam = new ArrayList <blackTeam>();
ArrayList <blueTeam> blueTeam = new ArrayList <blueTeam>();
ArrayList <greenTeam> greenTeam = new ArrayList <greenTeam>();
ArrayList <orangeTeam> orangeTeam = new ArrayList <orangeTeam>();
ArrayList <redTeam> redTeam = new ArrayList <redTeam>();
ArrayList <yellowTeam> yellowTeam = new ArrayList <yellowTeam>();

private void displaystatButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    //sort arrayList by goals/assists

}

EDIT: This is how my classes are set up, as well as how data is added to them. Hopefully this clears up some questions.

//add data to database
black = new blackTeam(jerseyNum, firstName, lastName, prefPosition, goals, assists);
blackTeam.add(black);

class blackTeam {
    int goals, assists;
    String jerseyNum, firstName, lastName, prefPosition;

    blackTeam (String _jerseyNum, String _firstName, String _lastName, String _prefPosition, int _goals, int _assists) {
        jerseyNum = _jerseyNum;
        firstName = _firstName;
        lastName = _lastName;
        prefPosition = _prefPosition;
        goals = _goals;
        assists = _assists;
    }
}

I have one these classes for each team.


回答1:


I suggest using Comparator on your object, let me assume it is Team

public class Team{
    private int jerseyNumber;
    private String lastName;
    ...
    public int getJerseyNumber(){
        return jerseyNumber;
    }
}

If you want to sort based on jersey number, generate JeseryNumberComaparator:

import java.util.Comparator;

public class JeseryNumberComaparator implements Comparator {

    @Override
    public int compare(Team t1, Team t2) {

        // descending order (ascending order would be:
        // t1.getJerseyNumber()-t2.getJerseyNumber())
        return t1.getJerseyNumber()-t2.getJerseyNumber()
    }
}

It will sort your list based on jersey number by:

Collections.sort(blackTeam, new JerseyNumberComparator());



回答2:


As long as your 6 classes blackTeam to yellowTeam all descend from the same parent, ie. that they are declared like this:

public class blackTeam extends Team { ... }

then you can make a new ArrayList<Team> and add them all to it:

ArrayList<Team> all = new ArrayList<>();
all.addAll(blackTeam);
all.addAll(blueTeam);
all.addAll(yellowTeam); 
// etc...

Then you can sort this list using an instance of Comparator<Team>. Since Java8, however, there's a much neater way to create a comparator using lambda expressions:

all.sort((a, b) -> a.getScore() - b.getScore()); // or whatever attribute you want to compare on

If you want to do it the old fashioned way instead, then you can create an anonymous class like this:

all.sort(new Comparator<Team>() {
    @Override
    public int compare(Team a, Team b) {
        return a.getScore() - b.getScore();
    }
});

They amount to the same thing, but the lambda based approach is a bit less wordy!

Note that i suspect you don't actually want to have 6 different classes for the different colours. Are you sure you have understood the role of a class properly?




回答3:


For sorting Collection in Descending order (other than their natural sort order), you have to define your own Comparator.

For sorting on a specific field individually (one at a time), you have to define separate Comparator implementation.

In your class, you can define two individual Comparators. Here is example code.

static final Comparator<Team> SORT_TEAM_BY_GOALS_DESCENDING = new Comparator<Team>(){
     public int compare(Team t1, Team t2){
          return t2.getGoals() - t1.getGoals();
     }
}

static final Comparator<Team> SORT_TEAM_BY_ASSIST_DESCENDING = new Comparator<Team>(){
     public int compare(Team t1, Team t2){
          return t2.getAssist() - t1.getAssist();
     }
}

Make sure that, normal sort is always natural order, in your case for int it is always Ascending. In order to have Descending order, you need to do t2 - t1. t1 - t2 will give you natural Ascending order.

Now in order to use this Comparator, just use following code.

Collections.sort(team, SORT_TEAM_BY_GOALS_DESCENDING);

or

Collections.sort(team, SORT_TEAM_BY_ASSIST_DESCENDING);

And off course, if all these different color List (i.e. blackTeam and so on) are only for specific team identified by color, than add one more field to your Team class called 'color` which will identify each player along with what team they belongs to.



来源:https://stackoverflow.com/questions/42121624/sort-arraylist-of-objects-by-specific-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!