Associative Array in Java

Mohammad Irfan Feb 07, 2022
  1. Use the Associative Array in Java
  2. Abstract of the Associative Array in Java
  3. Implement an Associative Array in Java
  4. Create an Associative Array in Java
  5. Add Elements to the Associative Array in Java
  6. Traverse Elements of the Associative Array in Java
  7. Traverse Elements of the Associative Array Using forEach() Method in Java 8
Associative Array in Java

An associative array is a type of array that stores the set of elements in key and value pairs. It is a collection of keys and values where the key is unique and is associated with one value.

If we have to access the element from the associative array, we must call the array’s name and pass the key whose value we want to access.

Use the Associative Array in Java

For example, we have an array named marks that stores the roll number and students’ marks.

So if we have to access the mark of a particular student, then we can call like this marks 105, where marks are the name of an array and 105 is the roll number of the student, not an index number which is not possible in an array if we are using Java language.

Therefore associative array does not support Java, but we can easily achieve it using HashMap. Java does not support associative array but can be implemented using the Map.

Abstract of the Associative Array in Java

HashMap<String, String> hashmap = new HashMap<>();
        // method to add the key,value pair in hashmap
        hashmap.put("Key1", "Value1");
        hashmap.put("Key2", "Value2");
        hashmap.put("Key3", "Value3");
		// and many more...
        // get the value 1 and 2
        System.out.println(hashmap.get("Key1"));
        System.out.println(hashmap.get("Key2"));
		// and many more...

Implement an Associative Array in Java

To implement an associative array in Java, we used HashMap, an implementation class of Map interface. Let’s understand step by step.

First, import and initialize the HashMap, i.e., create an instance of HashMap by using the following statements.

import java.util.HashMap;
HashMap<String, String> hashmap = new HashMap<>();

Then, using the put() method, add the key value to the HashMap.

hashmap.put("Key1", "Value1");

Convert the HashMap to Set using the entrySet() method to remove duplicate keys.

Set<Map.Entry<String ,String> > set = map.entrySet();

Convert the Set to an ArrayList which is an array that we want.

List<Map.Entry<String ,String>> list=new ArrayList<>(set);

Create an Associative Array in Java

In this example, we used the HashMap class to implement the associative array in Java.

See, it contains data in key-value pair format, and we used the getKey() method to access the key and the getValue() method to access values.

import java.io.*;
import java.util.*;
public class SimpleTesting {
    public static void main(String[] args) {
        HashMap<String, String> hashmap = new HashMap<>();
        hashmap.put("Virat", "Batsman");
        hashmap.put("Bumrah", "Bowler");
        hashmap.put("Jadeja", "All-rounder");
        hashmap.put("Pant", "Wicket-Keeper");

        Set<Map.Entry<String, String>> s = hashmap.entrySet();
        List<Map.Entry<String, String>> array = new ArrayList<>(s);
        for (int i = 0; i < array.size(); i++) {
            System.out.println(array.get(i).getKey() + " is " + array.get(i).getValue());
        }
    }
}

Output:

Pant is Wicket-Keeper
Jadeja is All-rounder
Bumrah is Bowler
Virat is Batsman

As we have already discussed, that key should be unique. If we insert the same keys in the associative array, it will discard one of the key-value pairs.

We have inserted two same keys, Virat, in the following code. See the example below.

import java.io.*;
import java.util.*;
public class SimpleTesting {
    public static void main(String[] args) {
        HashMap<String, String> hashmap = new HashMap<>();
        hashmap.put("Virat", "Batsman");
        hashmap.put("Bumrah", "Bowler");
        hashmap.put("Jadeja", "All-rounder");
        hashmap.put("Pant", "Wicket-Keeper");
        hashmap.put("Virat", "Captain");

        Set<Map.Entry<String, String>> s = hashmap.entrySet();
        List<Map.Entry<String, String>> array = new ArrayList<>(s);
        for (int i = 0; i < array.size(); i++) {
            System.out.println(array.get(i).getKey() + " is " + array.get(i).getValue());
        }
    }
}

Output:

Pant is Wicket-Keeper
Jadeja is All-rounder
Bumrah is Bowler
Virat is Captain

Add Elements to the Associative Array in Java

We can add an element to an array in the map by using the put() method. Similarly, we can remove an element from an array using the remove() method.

We can find out the size of the array by using the size() method.

import java.util.HashMap;
public class SimpleTesting {
    public static void main(String[] args) {
        HashMap<String, String> fruits = new HashMap<String, String>();
        fruits.put("Apple", "Red");
        fruits.put("Banana", "Yellow");
        fruits.put("Guava", "Green");
        fruits.put("Blackberries", "Purple");
        
        System.out.println("The Size of fruits Map is : " + fruits.size());
        // Remove Banana from the HashMap
        fruits.remove("Banana");
        // To find out the size of the Hashmap
        System.out.println("The Size of fruits Map is : " + fruits.size());
        // Check whether the key is present in the Hashmap or not
        String fruit_key = "Apple";
        if (fruits.containsKey(fruit_key)) {
            System.out.println("The colour of " + fruit_key + " is: " + fruits.get(fruit_key));
        } else {
            System.out.println("There is no entry for the fruit of " + fruit_key);
        }
    }
}

Output:

The Size of fruits Map is : 4
The Size of fruits Map is : 3
The colour of Apple is: Red

Traverse Elements of the Associative Array in Java

We can use the for-each loop to traverse the associative array. Since HashMap belongs to the java.util package, we can use the foreach loop to iterate its elements.

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

public class SimpleTesting {
    public static void main(String[] args) {

        HashMap<String, String> fruits = new HashMap<String, String>();
        fruits.put("Apple", "Red");
        fruits.put("Banana", "Yellow");
        fruits.put("Guava", "Green");
        fruits.put("Blackberries", "Purple");
        System.out.println("The Size of fruits Map is : " + fruits.size());
        for (Map.Entry element : fruits.entrySet()) {
            String key = (String) element.getKey();
            System.out.println(key + " : " + element.getValue());
        }
    }
}

Output:

The Size of fruits Map is : 4
Guava : Green
Apple : Red
Blackberries : Purple
Banana : Yellow

Traverse Elements of the Associative Array Using forEach() Method in Java 8

If you are working with Java 8 or a higher version, you can use the forEach() method to traverse the array elements. The forEach() method requires a lambda expression as an argument.

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

public class SimpleTesting {
    public static void main(String[] args) {
        HashMap<String, String> fruits = new HashMap<String, String>();
        fruits.put("Apple", "Red");
        fruits.put("Banana", "Yellow");
        fruits.put("Guava", "Green");
        fruits.put("Blackberries", "Purple");

        System.out.println("The Size of fruits Map is : " + fruits.size());
        fruits.forEach((k, v) -> System.out.println(k + " : " + v));
    }
}

Output:

The Size of fruits Map is : 4
Guava : Green
Apple : Red
Blackberries : Purple
Banana : Yellow

This tutorial studied that Java technically does not support the associative array, but we can easily achieve it using HashMap.

Related Article - Java Array