Changing specific value of HashMap key

Juho M Source

I have HashMap where key is bird specie and value is number of perceptions. Here is my code:

public class Program {

public static void main(String[] args) {

    HashMap<String, Integer> species = new HashMap<>();
    Scanner reader = new Scanner(System.in);

    species.put("hawk (buteo jamaicensis)", 0);
    species.put("eagle (aquila chrysaetos)", 0);
    species.put("sparrow (passeridae)", 0);

    System.out.println("Add perception");
    System.out.println("What was perceived?"); //output should be "hawk"/"eagle"/"sparrow"
    String perception = reader.nextLine();

    // Change here the value of hashmap key.

    ArrayList<String> list = new ArrayList<>();
    for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
        System.out.println((entry.getKey()+" : "+entry.getValue()+" perception"));
    }



}

My goal is to change key value to from 0 to 1, when scanner is asking what was perceived.

For example: Scanner is asking "What was perceived?" and output is "hawk". Then the program should change key "hawk (buteo jamaicensis)" value from 0 to 1. So the goal output would be now:

sparrow (passeridae) : 0 perception
eagle (aquila chrysaetos) : 0 perception
hawk (buteo jamaicensis) : 1 perception
javahashmapkey-value

Answers

answered 3 months ago JohnSnowDoesNotKnowNothing #1

Use String.indexOf check if the input string is substring of the key, and if it is, set the new value:

// Change here the value of hashmap key.
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
    if (entry.getKey().indexOf(perception) >= 0) {
        entry.setValue(entry.getValue() + 1);
}

answered 3 months ago Ann #2

for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
 if (entry.getKey().equals(perception)) {
 entry.setValue(entry.getValue() + 1);
 }
}

comments powered by Disqus