Hash Map iteration methods

//HM in UTIL
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HashMaapTutorial {
/*
 * HashMap ITERATION METHODS
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMaapTutorial hmTutorial = new HashMaapTutorial();
hmTutorial.TurorialMethod();
//==============================================

}

public void TurorialMethod() {
// HASH-MAP ==== "UTIL" package
Map<Integer, String> hm = new HashMap<Integer, String>();

hm.put(1, "Nihal"); // ADDING (K,V) to HahMap
hm.put(2, "Mike");
hm.put(3, "Kurre");
// ==========================PREFERRED WAYS

// lOOP IN 2 Methods
hm.forEach((k, v) -> System.out.println("Key: " + k + " Value: " + v)); // Can Be used iN Java-8 ONLY foreach
// and LAMBDA


///////////////////////////// BESTWAY  ///////////////////////////////
// Loop in method 2 //Best way to use
System.out.println("Method:2"); // Ternary ternary ----? :
for (Map.Entry<Integer, String> entry : hm.entrySet()) {
System.out.println("key:" + entry.getKey() + "vale: " + entry.getValue());
}
// =============================

// Map -> Set -> Iterator -> Map.Entry -> troublesome, not recommend!
System.out.println("\nExample 1..."); // Using ITERATOR
Iterator<Entry<Integer, String>> iterator = hm.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iterator.next();
System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
}

// more elegant way, this should be the standard way, recommend! //Writing 2nd
// time method //BEST way to use
System.out.println("\nExample 2..."); // Using MAP.Entry<>
for (Map.Entry<Integer, String> entry : hm.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}

// weird, but works anyway, not recommend!
System.out.println("\nExample 3..."); // Using Object key
for (Object key : hm.keySet()) {
System.out.println("Key : " + key.toString() + " Value : " + hm.get(key));
}

// ..............................................
// iterating over keys only using 2 For loops
for (Integer key : hm.keySet()) {
System.out.println("Key = " + key);
}

// iterating over values only
for (String value : hm.values()) {
System.out.println("Value = " + value);
}
// ...............................................

System.out.println("Iterating over keys and searching for values");
for (Integer key : hm.keySet()) {
String value = hm.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
}
}


No comments:

Post a Comment