fox.josh
fox.josh

Reputation: 185

Search HasMap value for String instance

I have a HashMap in my GUI class of:

HashMap<Integer, Party> partyInput = new HashMap<>();

and using a String input from user search the hashMap value for its instance. How do I cast the String to Party Object or Party Object to String? I can search easily the key and have several other programs that search for values of String but can not figure out this scenario. Trying:

// target is the value input from user by JTextField
if (partyInput.containsValue(target)) {

    }

gives me "Suspicious call to have.util.Map.containsValue: Given object cannot contains instances of String (expected Party)".

Party Class:

import java.util.ArrayList;


public class Party extends GameElement{

ArrayList<Creature> creature = new ArrayList<>();

public Party() {
   } // end default constructor

// constructor for all Party member fields
public Party (int index, String name) {
    // get fields from parent GameElement class
    super(index, name);
} // end Party constructor


// getter for creature members of each party
public ArrayList<Creature> getMembers() {
    return creature;
} // end getMemebers method

// setter for creature members of each party
public void setMembers(ArrayList<Creature> partyMembers) {
    this.creature = partyMembers;
} // end setMemebers method

@Override
public String toString() {

    StringBuilder sb = new StringBuilder();
    sb.append(String.format("%n**********************************************************"));
    sb.append(String.format("%nParty: %s%n", getName()));
    sb.append(String.format("Creatures %n"));
    creature.stream().forEach((c) -> {
        sb.append(String.format("**** %s%n", c.getName()));
    });

    return sb.toString();
} // end toString method
} // end Party class

Any assistance would be greatly appreciated.

Upvotes: 0

Views: 85

Answers (2)

Andy Turner
Andy Turner

Reputation: 140318

If the target String is the value of some property of Party, you need to just iterate the map's values looking for the instance with the matching attribute, e.g.

for (Party party : map.values()) {
  if (party.getTarget().equals(target)) {
    // Do whatever.
  }
}

Upvotes: 1

PA001
PA001

Reputation: 451

If you can construct a Party instance from a String then perhaps you could do something along the lines of:

if(partyInput.containsValue(new Party(text)) {
    // Do something
}

Assuming equals has been overridden appropriately.

Or you could iterate over the values set and try to match upon a property in your Party object.

    for(Party party  : m.values()) {
        if(text.equals(party.getXXX())) {
            // Do something
        }
    }

Upvotes: 2

Related Questions