An associative array stores the set of elements in the form of (key, value) pairs. An associative array is a collection of unique keys and collections of values where each key is associated with one value.
An associate array is an abstract datatype like a map that is composed of a (key, value) pair, such that each key-value appears at most once in the collection. Basically, an array with named indexes is known as an associative array or hashes.
In Java, it is difficult to form the associative array however this could easily be achieved using a HashMap:
Syntax:
Map<String, String> map = new HashMap<String, String>(); // method to add the key,value pair in hashmap map.put("geeks", "course"); map.put("name", "geeks"); // method to get the value map.get("name"); // returns "geeks"
Steps to implement the Associative array or associative the List Array using the Map Function :
1. First initialize the map
Map<String ,String> map = new HashMap<>();
2. Then Put the Key, Value to the map using put method
map.put("geeks","Course");
3. After putting all Key Value to the map Convert the map to set using the entrySet() Method
Set<Map.Entry<String ,String> > set = map.entrySet();
4. Then Now convert the set to the List Array using the function ;
List<Map.Entry<String ,String>> list=new ArrayList<>(set);
Implementation of associate array:
Java
// Java program to implement the associate array import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { // Forming the map Map<String, String> map = new HashMap<>(); // method to store the value and // key into the map map.put( "name" , "rohit" ); map.put( "geeks" , "course" ); map.put( "India Capital" , "Delhi" ); System.out.println(map.size()); Set<Map.Entry<String, String> > set = map.entrySet(); List<Map.Entry<String, String> > list = new ArrayList<>(set); for ( int i = 0 ; i < list.size(); i++) { System.out.println(list.get(i).getKey() + ": " + list.get(i).getValue()); } } } |
3 India Capital: Delhi geeks: course name: rohit
- Time Complexity: O(n)
- Space Complexity: O(n)
We can iterate through the array using the iterator() method
Syntax:
Iterator it = map.entrySet().iterator();
Java
// Java program to implement the associate array // and iterate it using iterator() method import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { // Forming the map Map<String, Integer> map = new HashMap<>(); // method to store the put the value and // key into the map map.put( "Roll no" , 45 ); map.put( "Total Question" , 113 ); map.put( "Marks " , 400 ); // method to access the value based on // the key System.out.println(map.size()); Set<Map.Entry<String, Integer> > set = map.entrySet(); List<Map.Entry<String, Integer> > list = new ArrayList<>(set); // using the iterator Iterator it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } |
3 Total Question=113 Roll no=45 Marks =400
- Time Complexity: O(n)
- Space Complexity: O(n)