Hashmaps in java example

Java HashMap

In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number ( int type). A HashMap however, store items in «key/value» pairs, and you can access them by an index of another type (e.g. a String ).

HashMap class stores data in «key and value» pairs: one object is used as a key (index) to another object (value), and is found in the java.util package.

One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like: String keys and String values:

Example

Create a HashMap object called capitalCities that will store String keys and String values:

import java.util.HashMap; // import the HashMap class HashMap capitalCities = new HashMap(); 

Add Items

The HashMap class has many useful methods. For example, to add items to it, use the put() method:

Читайте также:  Python input one character

Example

// Import the HashMap class import java.util.HashMap; public class Main < public static void main(String[] args) < // Create a HashMap object called capitalCities HashMapcapitalCities = new HashMap(); // Add keys and values (Country, City) capitalCities.put("England", "London"); capitalCities.put("Germany", "Berlin"); capitalCities.put("Norway", "Oslo"); capitalCities.put("USA", "Washington DC"); System.out.println(capitalCities); > > 

Access an Item

To access a value in the HashMap , use the get() method and refer to its key:

Example

Remove an Item

To remove an item, use the remove() method and refer to the key:

Example

capitalCities.remove("England"); 

To remove all items, use the clear() method:

Example

HashMap Size

To find out how many items there are, use the size() method:

Example

Loop Through a HashMap

Loop through the items of a HashMap with a for-each loop.

Note: Use the keySet() method if you only want the keys, and use the values() method if you only want the values:

Example

// Print keys for (String i : capitalCities.keySet())

Example

// Print values for (String i : capitalCities.values())

Example

// Print keys and values for (String i : capitalCities.keySet())

Other Types

Keys and values in a HashMap are actually objects. In the examples above, we used objects of type «String». Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer . For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

Example

Create a HashMap object called people that will store String keys and Integer values:

// Import the HashMap class import java.util.HashMap; public class Main < public static void main(String[] args) < // Create a HashMap object called people HashMappeople = new HashMap(); // Add keys and values (Name, Age) people.put("John", 32); people.put("Steve", 30); people.put("Angie", 33); for (String i : people.keySet()) < System.out.println("key: " + i + " value: " + people.get(i)); >> > 

Источник

HashMap in Java With Examples

HashMap is a Map based collection class that is used for storing Key & value pairs, it is denoted as HashMap or HashMap. HashMap in java, is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).

It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. It does not sort the stored keys and values. You must need to import java.util.HashMap or its super class in order to use the HashMap class and methods.

HashMap

Let’s discuss HashMap in detail.

  • In key-value pairs, the key must be unique.
  • It is non-synchronized. However you can make it synchronized.
  • Doesn’t maintain insertion order.
  • Doesn’t sort elements
  • It allows null keys and values. However only one null key is allowed. Multiple null values are allowed.

HashMap class hierarchy

HashMap in Java

How to declare HashMap in Java?

HashMap hmap = new HashMap();

K: It represents the type of the key in a key-value pair.
V: It represents the type of a value in a key-value pair.

For example: A HashMap that has integer keys and string values can be declared like this:

HashMap hmap = new HashMap();

HashMap in Java Examples

1. Adding elements to HashMap

You can use the put() method of the HashMap class to add new key-value pairs to the HashMap. To iterate the HashMap, we are using entrySet() method. This method returns an equivalent Set. This is to pass the key-value pairs to the Map.Entry, which contains the methods getKey() and getValue() that we can use to print key-value pairs of HashMap. HashMap elements are traversed using for loop and key-value pairs are printed.

import java.util.*; public class JavaExample < public static void main(String args[])< HashMaphMap=new HashMap<>(); hMap.put(101,"Cricket"); hMap.put(105,"Hockey"); hMap.put(111,"Basketball"); System.out.println("HashMap elements: "); for(Map.Entry mEntry : hMap.entrySet()) < System.out.print("key: "+ mEntry.getKey() + " & Value: "); System.out.println(mEntry.getValue()); >> >

HashMap in Java Example output

Output:

2. Checking duplicate key insertion in HashMap

Here, we are trying to add element with a duplicate key. The new element (111,”Karate”) has the key value 111, which is already present in the HashMap. Instead of adding this new element, HashMap updated the value of already existing element with key “111”.

import java.util.*; public class JavaExample < public static void main(String args[])< HashMaphMap=new HashMap<>(); hMap.put(101,"Cricket"); hMap.put(105,"Hockey"); hMap.put(111,"Basketball"); hMap.put(111,"Karate"); //adding element with duplicate key System.out.println("HashMap elements: "); for(Map.Entry mEntry : hMap.entrySet()) < System.out.print("key: "+ mEntry.getKey() + " & Value: "); System.out.println(mEntry.getValue()); >> >

HashMap duplicate key example

Output:

3. HashMap remove() method Example

import java.util.*; public class JavaExample < public static void main(String args[])< HashMaphMap=new HashMap<>(); hMap.put(101,"Cricket"); hMap.put(105,"Hockey"); hMap.put(111,"Basketball"); //this will remove the key-value pair where //the value of the key is 101 hMap.remove(101); System.out.println("HashMap elements: "); for(Map.Entry mEntry : hMap.entrySet()) < System.out.print("key: "+ mEntry.getKey() + " & Value: "); System.out.println(mEntry.getValue()); >> >
HashMap elements: key: 105 & Value: Hockey key: 111 & Value: Basketball

4. HashMap replace() method Example

import java.util.*; public class JavaExample < public static void main(String args[])< HashMaphMap=new HashMap<>(); hMap.put(101,"Cricket"); hMap.put(105,"Hockey"); hMap.put(111,"Basketball"); //this will update the value of key-value pair //where the key is 105 hMap.replace(105, "Kickboxing"); System.out.println("HashMap elements: "); for(Map.Entry mEntry : hMap.entrySet()) < System.out.print("key: "+ mEntry.getKey() + " & Value: "); System.out.println(mEntry.getValue()); >> >
HashMap elements: key: 101 & Value: Cricket key: 105 & Value: Kickboxing key: 111 & Value: Basketball

Internal working of HashMap in Java

HashMap internally uses a technique called hashing to generate index for keys. This indexing allows faster searching of record. This allows faster response time for operations such as search, update, delete etc.

When we call the HashMap put() method as shown in the following statement. It calculates the hash code of the key (101 in this case) using hash function. This hash code is calculated using the hashing technique. An index is assigned to this hash code. This index uniquely identifies this key-value pair.

HashMap hMap=new HashMap<>(); hMap.put(101,"Cricket");

When a duplicate key is inserted into the HashMap, Hash Collision happens. HashMap handles this by updating the old value with the new value.

HashMap Class Methods

Here is the list of methods available in HashMap class. I have also covered examples using these methods at the end of this post.

  1. void clear(): It removes all the key and value pairs from the specified Map.
  2. Object clone(): It returns a copy of all the mappings of a map and used for cloning them into another map.
  3. boolean containsKey(Object key): It is a boolean function which returns true or false based on whether the specified key is found in the map.
  4. boolean containsValue(Object Value): Similar to containsKey() method, however it looks for the specified value instead of key.
  5. Value get(Object key): It returns the value for the specified key.
  6. boolean isEmpty(): It checks whether the map is empty. If there are no key-value mapping present in the map then this function returns true else false.
  7. Set keySet(): It returns the Set of the keys fetched from the map.
  8. value put(Key k, Value v): Inserts key value mapping into the map. Used in the above example.
  9. int size(): Returns the size of the map – Number of key-value mappings.
  10. Collection values(): It returns a collection of values of map.
  11. Value remove(Object key): It removes the key-value pair for the specified key. Used in the above example.
  12. void putAll(Map m): Copies all the elements of a map to the another specified map.

HashMap Example to demonstrate various methods

In this example we have demonstrated almost all the important methods of HashMap class.

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class Details < public static void main(String args[]) < /* This is how to declare HashMap */ HashMaphmap = new HashMap(); /*Adding elements to HashMap*/ hmap.put(12, "Chaitanya"); hmap.put(2, "Rahul"); hmap.put(7, "Singh"); hmap.put(49, "Ajeet"); hmap.put(3, "Anuj"); /* Display content using Iterator*/ Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) < Map.Entry mentry = (Map.Entry)iterator.next(); System.out.print("key is: "+ mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); >/* Get values based on key*/ String var= hmap.get(2); System.out.println("Value at index 2 is: "+var); /* Remove values based on key*/ hmap.remove(3); System.out.println("Map key and values after removal:"); Set set2 = hmap.entrySet(); Iterator iterator2 = set2.iterator(); while(iterator2.hasNext()) < Map.Entry mentry2 = (Map.Entry)iterator2.next(); System.out.print("Key is: "+mentry2.getKey() + " & Value is: "); System.out.println(mentry2.getValue()); >> >
key is: 49 & Value is: Ajeet key is: 2 & Value is: Rahul key is: 3 & Value is: Anuj key is: 7 & Value is: Singh key is: 12 & Value is: Chaitanya Value at index 2 is: Rahul Map key and values after removal: Key is: 49 & Value is: Ajeet Key is: 2 & Value is: Rahul Key is: 7 & Value is: Singh Key is: 12 & Value is: Chaitanya

HashMap Tutorials

Here is the list of tutorials published on HashMap class. Happy Learning:)

HashMap Basics

Serialize/Synchronize

Источник

Hashmaps in java example

“Анна Ивановна Решетникова, 4211 717171” И как они собирались хранить такой номер паспорта в типе Integer? Тем самым показав, что номер паспорта хранить в базе данных как число — это не лучшая идея. Так как номера паспорта могут содержать дефисы, пробелы, буквы и т.д. Поправьте меня, если я не прав. Иначе у меня вопросы к господину Милану.

Скажите, почему хронология вывода на экран поменялась?

Получение списка всех ключей и значений Еще одна удобная особенность HashMap — можно по-отдельности получить список всех ключей и всех значений. Для этого используются методы keySet() и values() Для чего в примере создаются Set и ArrayList? Если в sout можно прямо вызвать методы keySet() и values()?

Возможно ли в HashMap переопределить метод toString() и если да, то каким образом? P/S: Спросил нынче модный ChatGPT, так он какую-то чушь городит: то пишет можно и даёт нерабочие коды, каждый раз разные, то пишет что нельзя потому что HashMap происходит от абстрактного класса. Хотя я уже понял что верить ему нельзя во всем, на вопрос можно ли реализовать в Java множественное наследование (не через интерфейсы) он бодро рапортовал, что конечно можно и вывалил код типа public сlass A extends B, C, который естественно не работает. Извините за возможный оффтоп. Так что роботы пока не завоюют мир, поэтому, вопрос по toString() все еще актуален. )

Источник

Hashmaps in java example

Let’s see a simple example of HashMap to store key and value pair.

Iterating Hashmap. 1 Mango 2 Apple 3 Banana 4 Grapes

In this example, we are storing Integer as the key and String as the value, so we are using HashMap as the type. The put() method inserts the elements in the map.

To get the key and value elements, we should call the getKey() and getValue() methods. The Map.Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.Entry.

No Duplicate Key on HashMap

You cannot store duplicate keys in HashMap. However, if you try to store duplicate key with another value, it will replace the value.

Iterating Hashmap. 1 Grapes 2 Apple 3 Banana

Java HashMap example to add() elements

Here, we see different ways to insert elements.

Initial list of elements: <> After invoking put() method 100 Amit 101 Vijay 102 Rahul After invoking putIfAbsent() method 100 Amit 101 Vijay 102 Rahul 103 Gaurav After invoking putAll() method 100 Amit 101 Vijay 102 Rahul 103 Gaurav 104 Ravi

Java HashMap example to remove() elements

Here, we see different ways to remove elements.

Initial list of elements: Updated list of elements: Updated list of elements: Updated list of elements:

Java HashMap example to replace() elements

Here, we see different ways to replace elements.

Initial list of elements: 100 Amit 101 Vijay 102 Rahul Updated list of elements: 100 Amit 101 Vijay 102 Gaurav Updated list of elements: 100 Amit 101 Ravi 102 Gaurav Updated list of elements: 100 Ajay 101 Ajay 102 Ajay

Difference between HashSet and HashMap

HashSet contains only values whereas HashMap contains an entry(key and value).

Java HashMap Example: Book

1 Details: 101 Let us C Yashwant Kanetkar BPB 8 2 Details: 102 Data Communications and Networking Forouzan Mc Graw Hill 4 3 Details: 103 Operating System Galvin Wiley 6

Источник

Оцените статью