QA's approach 2 Java - Map Interface with Examples

Map Interface

Used for storing key value pairs

Linked HashMap:

Will retain the Entries in the insertion order. 

HashMap:

Will not retain the Entries in the insertion order. 

Methods in Map Interface:

public Object put(Object key, Object value): 
This method is used to insert an entry in this map.

public void putAll(Map map): 
This method is used to insert the specified map in this map.

public Object remove(Object key): 
This method is used to delete an entry for the specified key.

public Object get(Object key):
This method is used to return the value for the specified key.

public boolean containsKey(Object key): 
This method is used to search the specified key from this map.

public Set keySet(): 
This method is used to return the Set view containing all the keys.

public Set entrySet(): 
The entrySet( ) method declared by the Map interface returns a Set containing the map entries. 
Each of these set elements is a Map.Entry object.
Usually we use this to get the keys and values from a map.

Map.Entry Interface
This describes an element (a key/value pair) in a map. This is an inner class of Map.
The Map.Entry interface enables you to work with a map entry.
Its used hold a single entry of key value.


Linked HashMap:

Usage -> Will retain the Entries in the insertion order. Example below will indicate the usage

package collectPractise;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class GetFirstNonRepeatedChar {

public static void main(String[] args) {
  System.out
    .println("First non repeated character for String analogy is : "
      + getNonRepeatedCharacter("analogy"));
  System.out
    .println("First non repeated character for String easiest is : "
      + getNonRepeatedCharacter("easiest"));
}

public static Character getNonRepeatedCharacter(String str) {
  Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>();
  for (int i = 0; i < str.length() - 1; i++) {
   Character c = str.charAt(i);
   if (!countCharacters.containsKey(c)) {
    countCharacters.put(c, 1);
   } else {
    countCharacters.put(c, countCharacters.get(c) + 1);
   }
  }
  // As LinkedHashMap maintains insertion order, first character with
  // count 1 should return first non repeated character
  for (Entry<Character, Integer> e : countCharacters.entrySet()) {
   if (e.getValue() == 1)
    return e.getKey();

  }
  return null;

}
}



Sample Examples:
Program 1:

// Program to add entries to a Map & iterate over it

package com.CollectionsPractice;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Demo {

public static void main(String[] args) {

// Program to add entries to a Map & iterate over it

Map<String, Integer> obj = new HashMap<String, Integer> ();

// Add Book details with Price of each

obj.put("Java Black book", 1500);

obj.put("Python Programming", 1200);

obj.put("Devops Complete Solution", 2500);

// return a set view of the mappings contained in this map
Set s = obj.entrySet();

// Call the iterator method on the Set view of mappings to iterate over
Iterator itr = s.iterator();

while (itr.hasNext()) {

// Retrieves entry by entry from the Map & stores in Entry -> Individual Key & Value pairs

Map.Entry<String, Integer> entries = (Map.Entry<String, Integer>) itr.next();

// result will be returned in a random order, as HasMap doesn't  maintain the order of insertion
System.out.println("" + entries.getKey() + ": " + entries.getValue());

}


Output is as follows:
Devops Complete Solution: 2500
Java Black book: 1500
Python Programming: 1200


Program 1: Alternative solution

// Program to add entries to a Map & iterate over it

package com.CollectionsPractice;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Demo {

public static void main(String[] args) {

// Program to add entries to a Map & iterate over it

Map<String, Integer> obj = new HashMap<>();

// Add Book details with Price of each

obj.put("Java Black book", 1500);

obj.put("Python Programming", 1200);

obj.put("Devops Complete Solution", 2500);

//obj.entrySet results in set view of entries, where each entry of key-Value pair can be stored resulted can be stored in Map.Entry
for (Map.Entry<String, Integer> entry : obj.entrySet())

//entry.getKey()  will retrieve the Key for that entry while iterating over the entrySet

// entry.getValue() will retrieve the value for that entry while iterating over the entrySet

             System.out.println(entry.getKey() + ": " + entry.getValue());
                    }
                    }


Program 2:

     // Program to find occurances of the characters within the string

package com.CollectionsPractice;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Demo {

public static void main(String[] args) {

Map<Character, Integer> obj = new HashMap<>();
String s = "Program to print the count of each character in a sentence";

for (int i = 0; i < s.length(); i++) {
char value = s.charAt(i);
if (Character.isAlphabetic(value)) {
if (obj.containsKey(value)) {
obj.put(value, obj.get(value) + 1);

} else {
obj.put(value, 1);
}

}

}

for (Map.Entry<Character, Integer> entry : obj.entrySet())
System.out.println(entry.getKey() + ": count equals " + entry.getValue());

}

Output:

a: count equals 5
c: count equals 5
e: count equals 6
f: count equals 1
g: count equals 1
h: count equals 3
i: count equals 2
m: count equals 1
n: count equals 5
o: count equals 4
P: count equals 1
p: count equals 1
r: count equals 5
s: count equals 1
t: count equals 6
u: count equals 1

Storing list of maps 

List of all students Data 

List<Map<String, List<String>>> listOfMapOfList =  new HashList<Map<String, List<String>>>();

List of marks in all subjects stored against the students name

Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();

mapOfList.put("mykey", Arrays.asList("one", "two", "three"));

listOfMapOfList.add(mapOfList);

Comments

Popular posts from this blog

QA's approach 2 Java - Understanding Static context

Selenium 4 absolute beginners - How to create Batch execution file

Technologies - Log4J - Create Log4j Configuration File - Where ? How ? What ?