settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: How to create a Map in Java?

+13 votes

How can I make a Map in Java (with Keys and Values)? Can you please give me some examples of Map's usage in Java? Thank you!

asked in Java category by user nikole
edited by user golearnweb

1 Answer

+1 vote
 
Best answer
  • To add an item in a map use the method: .put() and inside the brackets put your Key and Value (line 8);
  • To get a Key and a Value you are using the method: .get() and inside the brackets put the Key (NOT the Value - otherwise a null will be shown in the console) (line 15)
  • To remove Key + Value use the method: .remove() and inside the brackets put the Key (line 18)

See the code and read the comments to clear things up:

import java.util.HashMap;
import java.util.Map;

public class HashMapCode {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();//CREATING A MAP

        map.put("Germany", "Berlin");//ADDING AN ITEM TO A MAP<Key, Value>
        map.put("Spain", "Madrid");
        map.put("Greece", "Athens");
        map.put("Turkey", "Ankara");

        System.out.println(map);

        String capital = map.get("Germany");//GETTING THE Value OF THE Key: Germany
        System.out.println("The capital of Germany is: " + capital);

        map.remove("Spain");//REMOVING A Key+Value

        System.out.println(map);
    }
}
answered by user mitko
edited by user golearnweb
...