How to store and modify maps? map.put(key,value);
Whether the map contains the element map.containskey (key);
Map the value of a key map.get(key);
Reference code
Import? Java . util . hashmap;
Public? Class? BookTest? {
Static electricity HashMap & lt string,? Integer & gt? Map = new? HashMap & lt string,? Integer & gt ();
Static{// Initializes the book information.
Map.put ("reflection", 8);
Map.put (A Dream of Red Mansions)? 0);
Map.put (The Journey to the West,? 15);
}
Public? Static electricity Invalid? main(String[]? args)? {//main method
Shu Jie (Water Margin);
Shu Jie (Romance of the Three Kingdoms);
Return the book (The History of the Three Kingdoms);
Shu Jie (A Dream of Red Mansions);
Return the book (A Dream of Red Mansions);
Shu Jie (A Dream of Red Mansions);
}
Public? Static electricity Invalid? Shu Jie (string? Name) {//Borrowing books
If (! Map.containsKey(name)){// Check whether the library has this book.
System. out.println ("book:"+name+"\ tThere is no such book!" );
Return;
}
if(map . get(name)& lt; =0){// Query whether the number of books is 0.
System.out.println ("Books:" +name+"\t have all been lent out, please come back tomorrow ");
Return;
}
Map.put (name, map.get (name)-1);
System. out.println ("books:"+name+"\ tBorrowing books succeeded." +" \ t inventory:"+map . get(name));
}
Public? Static electricity Invalid? Return the book (string? Name) {//Return the book
If (! map.containsKey(name)){
System.out.println ("book not found");
} Otherwise {
Map.put (name, map.get (name)+1);
System. out.println ("book:"+name+"\ tThe book has been returned successfully." +" \ t inventory:"+map . get(name));
}
}
} test output
Books: Water Margin Tea has no such books!
Books: The Three Kingdoms borrowed books successfully. Inventory: 7
Books: The Three Kingdoms successfully returned books. Inventory: 8
Books: A Dream of Red Mansions has all been lent out. Please come back tomorrow.
Books: A Dream of Red Mansions was returned successfully. Inventory: 1
Books: A Dream of Red Mansions borrowed books successfully. Inventory: 0