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
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
Map<String, String> map = new HashMap<>();
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());
}
}
}
|
Output3
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
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
Map<String, Integer> map = new HashMap<>();
map.put( "Roll no" , 45 );
map.put( "Total Question" , 113 );
map.put( "Marks " , 400 );
System.out.println(map.size());
Set<Map.Entry<String, Integer> > set
= map.entrySet();
List<Map.Entry<String, Integer> > list
= new ArrayList<>(set);
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
|
Output3
Total Question=113
Roll no=45
Marks =400
- Time Complexity: O(n)
- Space Complexity: O(n)