Print each element from an associative array in Java

In this tutorial, we will learn how to print each element in the associative array in Java, yes there are many ways to do so but here I want to make this tutorial easy to understand for you and learning very easy.

So, I am going to make this tutorial interesting for you and I hope you also you are excited to see how we can print elements from an associative array in java.

 Associative array in java

First of all, lets us know what is an associative array in java. An associative array in java is a collection of unique keys and values where each key is in association with particular values. It is the abstract data type and is similar to a hashmap(key, value) pair, in which at most once a key appears.

Let us understand with a real-life example:

suppose we need to store marks of two different subjects of the student then a numerically indexed array is the best option.

An array with named indexes is known as hashes and aka associative array and can be implemented in java using a hashmap.

Implementing associative array

As we know we can implement associative array in Java using hashmap. So, we need to know a few implementations of hashmap like initializing a hashmap. Then add keys and values to it.  How to fetch key values from a hashmap.

Follow the below example:

HashMap<String, Integer> map = new HashMap<>();

map.put("Maths", 95); //adding key and value to hashmap
map.put("English", 81);

map.get("English"); // return 81.

No further steps include:

After adding unique keys and values to the map now convert it into a set using the entrySet() method in hashmap.

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

Once entry set is created now convert it to list.

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

Sample code:

import java.io.*; // important header files
import java.util.*;
class GFG {
    public static void main(String[] args)  // main method
    {
        // initializing map
        Map<String, Integer> map = new HashMap<>();
        
       // adding key and values to map using put method in hashmap
        map.put("Maths", 92);
        map.put("English", 80);
        map.put("Total", 172);
  
        Set<Map.Entry<String, Integer> > myset = map.entrySet();
        
        List<Map.Entry<String, Integer> > mylist = new ArrayList<>(set);
        
        // using the iterator printing both key and value
        Iterator it = list.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

 

Output:

Maths: 92
English: 80
Total: 172

 

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Hope you liked this tutorial and learned a new concept.

Also read: Initialize a HashMap in JavaWorking with HashMap (Insertion, Deletion, Iteration) in Java

Leave a Reply

Your email address will not be published. Required fields are marked *