Checking if an ArrayList exists in a map - java

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);
}

Related

How to Determine If a Collection Is Empty

I have a 3 dimensional ArrayList and I want to determine if it is empty or not. There is an exception called EmptyCollectionException which is not part of java standard library and hence I'm not allowed to use it.
Is there a way to accomplish that using a native java exception or function?
The 3D List is constructed as follow:
public void makeRandomCardListForLearning (Course courseToBeMadeRandom) {
List<List<List<Card>>> course = new ArrayList<List<List<Card>>>();
for(Chapter chptr: courseToBeMadeRandom.getChapterList()) {
List<List<Card>> chapter = new ArrayList<List<Card>>();
course.add(chapter);
for(Deck dck: chptr.getDeckList()) {
List<Card> deck = new LinkedList<Card>();
chapter.add(deck);
for(Card crd: dck.getCardList()) {
if(dck.isTheCardDueToday(crd.getLastDate())) {
deck.add(crd);
}
}
Collections.shuffle(deck);
}
}
}
As I go through course, chapter and deck I create a List for each one. There is only one course, many chapters, many decks and of course many cards which are saved under deck doublyLinkedList if they pass the pre-condition. If no card passes the condition, I have a 3D list which exists but has no cards. And I want to determine that If no card exists in the list, then the user receives an error message.
In fact I only need the cards. But I also need to know in which deck each card resides at the moment. If I just make a list and go through all chapters and decks and put cards in that list based on the condition then I have no clue in which chapter and deck each card resides. That can be solved by maybe adding two attributes to the card class. But that was a mistake as we designed the system and adding them now costs a lot of change in other parts of the program. Each index in course List represents the chapter number and each index in chapter list represents the deck number. I solved the problem that way.
This should do it:
public static boolean isEmpty(List<List<List<Card>>> list3d) {
return list3d.stream().flatMap(llc -> llc.stream()).flatMap(lc -> lc.stream()).count() == 0;
}
It takes into account that the outer lists may contain empty inner lists. It deems the entire 3D list empty if there are no cards in it.
you can do something like this
List<List<List<Card>>> course = new ArrayList<List<List<Card>>>();
// some possible codes
boolean check = course.isEmpty()
// other possible codes
if (check) {
// do something
}
or any arraylist you want to check or any way you want to reach your goal

Iterating a loop through all objects of a class

New to Java-
I'm building a poker program and I've created a player class with some instance variables including "toppair", "highcardst",etc... I tried to use a placeholder variable to refer to the appropriate player's instance variable rather than relying on if statements.
int handsdealt=0;
int straightval=0;
String placeholder="blank";
player playerone = new player("Richard");
player playertwo = new player("Negreanu");
//code omitted
if (handsdealt==1) placeholder="playerone";
else placeholder="playertwo";
//code to determine if hand is a straight -if it is it sets straightval to 1
**if(straightval==1) placeholder.highcardst=straightHigh;**
I receive an error on that last line- it looks like java doesn't accept this syntax. Essentially, since this hand is a straight I want to append the value of the "highcardst" instance variable of the "n" th player as n hands have been dealt.
Thank you.
You seem to be uses a String for your placeholder variable where you actually want to refer to a player object.
player playerone = new player("Richard");
player playertwo = new player("Negreanu");
//code omitted
player placeholder;
if (handsdealt==1) placeholder=playerone;
else placeholder=playertwo;
//code to determine if hand is a straight -if it is it sets straightval to 1
if(straightval==1) placeholder.highcardst=straightHigh;
Also, it will make your code easier to follow if you follow normal Java code conventions, such as capitalising the first letter of a class name (e.g. Player, not player).
You could make a list of players and get the instance of the player from the list as required.
List<player> players = new ArrayList<player>();
players.add(new player("Richard"));
players.add(new player("Negreanu"));
if(straightval==1) {
players.get(handsdealt).highcardst=straightHigh;
}
Or something like that.
I think the problem could be in this statement:
placeholder.highcardst=straightHigh;
You've defined placeholder of type String, so the property called highcardst does not exist.
if(straightval==1) placeholder.highcardst=straightHigh;
Error is here. place holder is String type not Player type. Make temp variable as Player variable and assign
Player placeholder;
if (handsdealt==1) placeholder=playerone;

Edit Specific Instance of Object

Say i let players create teams and creating a team calls a new instance of the team class which has an array list called members.
Now in the main class how would i add a player to a team after being invited? i have an addPlayer method in the team class that simply add them to the arraylist but what if there are currently multiple instances of the teams class(other players have created teams) how would it know which one to join?
I do have a variable in the Teams class for the teamLeader which gets set when creating the instance if that could help me edit a certain instance.
Team team = new Team(this, leader);
Any help is appreiciated
You need an identifier to uniquely distinguish each team and you can use that identifier to store the teams in a Map. Something like this:
Map<String,Team> teamMap = new HashMap<String,Team>();
Chose the key type as per your requirement, I chose String for an example
As per your design, You need to keep all teams in a list after creation.
ArrayList teamsList=new ArrayList ();
Team team = new Team(this, leader);
teamsList.add(team);
Then Loop through all teams in addPlayer method and then compare leader and then add a player to it. Something like this -
public void addPlayer (Player player,String leader){
for(int i=0; i<teamListSize;i++)
Team tempTeam=teamsList.get(i);
if(tempTeam.getLeader().equalsIgnoreCase(leader)){
tempTeam.add(player);
break;
}
}

Keeping track of scores in Java

I'm new to Java and I'm currently writing a program for an assignment that represents a 'sports league' (classes to represent player/club/match/league)
My main problems are occurring in the league class. Here are the relevant variables to give you an idea how I'm storing things:
public class League
{
private String leagueName;
private ArrayList<Club> clubs;
private ArrayList<Match> fixtures;
private ArrayList<String> results2;
private TreeMap<Match, String> results;
private String topTeam;
private String goldenBoot;
}
Currently trying to write a method in the League class which will print a 'league table' - i.e. a list of Clubs sorted by their points tally (held as variable in Club class) and I'm drawing a blank on it.
Further to this, I need to write two methods to find the top scorer (golden boot) and find the top team in the league; again I am drawing a blank. Perhaps I am overcomplicating things?
Would be very grateful for suggestions/sample methods
EDIT:
Ok, so that method I'm trying to write is something beginning with:
public void getLeagueTable() {
for(Club c : clubs) {
c.getTally();
}
}
which would give the tally value for each Club object - but how to sort these results, and how to associate the highest with one Club is what's really troubling.
To print the league table, you are going to need to sort the club array and then loop through each item and print the club name.
To sort the club array try using Collections.sort http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
.. that is assuming you havent been told to implement your own algorithm
Again, more sorting required to get the top team and top scorer, then you will need to pick the top item from the sorted list.
Hope that helps...
You better use Set rather than ArrayList. And here is a good start for your question :
void printLeagueTable(){
i = 0 ;
while( i != clubs.size() ){
Club club = clubs.get(i);
System.out.println("club: "+i+ "points: " club.points() );
}
}

Reading text file with multiple columns with logic

I'm reading a text file that has multiple columns and I'm storing the information in an array
File looks like this
Player | Team
---------| ---------
PlayerA | Team1
PlayerA | Team2
PlayerB | Team3
PlayerC | Team4
PlayerC | Team5
As you see each player has multiple teams. I am trying to read this file line by line so that at the end of the file I have a List with three players (A, B, and C) and each having their corresponding teams.
Classes:
Player - with Name and List<Team> (getter setter for both)
Team - with Name (getter and setter)
I can't figure out the logic of when to create the Player and Team classes and keep account for when the player name has changed
You can encapsulate your person and team inside two classes Person and Team..
Then, You can use a Map<Person, List<Team>> to maintain various teams for each Person..
Map<Person, List<Team>> mapping = new HashMap<>();
// Read each line from file..
// Get Person and Team object..
// Assuming that you have your `Person` object in person and `Team` object in team
// You need a Comparator for `Person` class to check for `containment`..
if (mapping.contains(person)) {
// Person already exist.. Update the list of Team he has
mapping.get(person).add(team);
} else {
// New entry.. create a new list.. and add it to map..
List<Team> teamList = new ArrayList<>();
teamList.add(team);
mapping.put(person, teamList);
}
NOTE : - You need to have a Comparator for your Person class to be compared..
I think I have given you a base to work upon.. Rest you need to workaround.. How to populate your object.. How to implement Comparator.. and all that..
Typically I would not question the validity of the model proposed but ... does not make more sense that the teams are those that have many players rather than the opposite?
Anyhow, assuming that the player name cannot be changed by a team appearing again with a different player name:
BufferedReader input = ...;
Map<String,Player> playersByName = new HashMap<String,Player>();
String line;
while ((line = input.readLine()) != null) {
String playerName;
String teamName;
// code to parse the player and team names from 'line' comes here.
Player player = playersByName.get(playerName);
if (player == null)
playersByName.put(playerName,player = new Player(playerName));
Team team = new Team(teamName);
if (!player.getTeams().contains(team))
player.getTeams().add(team);
}
The code assumes that the Player constructor creates an empty list of teams.
Although the above will work using a list to hold the teams for a player I would suggest that you use a Set instead for efficiency if the number of teams that player has can be quite big. In that case you do not need the last conditional, you could add directly.
Even better if you hide the List or Set implementation entirely and you add operations to manipulate the team list safely within the Player class.
Remeber that if you use a (hashed) Set solution (hidden or exposed) you'll need to override the equals and hashCode functions appropriately in the Team class (delegating them on its name would work very well).

Categories