简体   繁体   中英

Checking if an ArrayList exists in a map

My football team has 5 different teams and I am trying to make a program to keep a track of which players are registered with each team. I want to be able to add a new player but first the program checks if that player is already registered. I would also be able to add new teams in the future and again I would like to check if that team already exists.

I have made a Map variable with

private Map<String, List<Player>> teamName;

then initialised this in the constructor

teamName = new HashMap<>();

I then have a method to add new teams and new players, I want the method to check if the Club name already exists and then if it does exist, add the player name to that Club. if it doesn't exist then I want the program to add a new Club and then add that player to that club.

So far I have a method for adding a new player,

public void newPlayer(String club, Player name) {
}

I am not sure how I now go about checking that an ArrayList exists for club and if it does add name to this list, if club does not exist then I want to make a new list and add name to it.

if I then run the program and write,

Player jamesAtkinson = new Player();

newPlayer("first team", jamesAtkinson);

it would check if there is a List in the Map called 'first team' and then either add James Atikinson to it, or create a new List called first team and then add James Atkinson.

Is this even possible to do?

Although there are a few problems with code you've provided in the question. What you're looking for is the .containsKey function that hangs off of the Map interface.

if (players.containsKey("first team") {
     // Do something
} else {
     List<Player> firstTeam = new ArrayList<>();
     firstTeam.add(jamesAtikson);
     players.put("first team", jamesAtikson);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM