Iterate the Entry // Java program to demonstrate iteration over // Map.entrySet() entries using for-each loop import java.util.Map; import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put("GFG", "geeksforgeeks.org"); gfg.put("Practice", "practice.geeksforgeeks.org"); gfg.put("Code", "code.geeksforgeeks.org"); gfg.put("Quiz", "quiz.geeksforgeeks.org"); // using for-each loop for iteration over Map.entrySet() for …
HashMap computeIfAbsent() method in Java with Examples
The computeIfAbsent(Key, Function) method of HashMap class is used to compute value for a given key using the given mapping function, if key is not already associated with a value (or is mapped to null) and enter that computed value in Hashmap else null. If mapping function of this method returns null, then no mapping …
Continue reading “HashMap computeIfAbsent() method in Java with Examples”
Sorting a HashMap according to keys in Java
Using TreeMap // Java Code to sort Map by key value import java.util.*; class sortmapKey { // This map stores unsorted values static Map<String, Integer> map = new HashMap<>(); // Function to sort map by Key public static void sortbykey() { // TreeMap to store values of HashMap TreeMap<String, Integer> sorted = new TreeMap<>(); // …
Continue reading “Sorting a HashMap according to keys in Java”
Java Iterate through a HashMap Example
Using for each to iterate through a HashMap Using for each to iterate through a HashMap import java.util.HashMap; import java.util.Map; public class IterateHashMap { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); …