Iterating Map In Java 8
Introduction
Java 8 introduced a lot of new features and improvements, one of which is the iteration of maps. Iterating through maps was a bit tricky in previous versions, but Java 8 made it much easier and more efficient.
What is a Map?
A map is a collection of key-value pairs, where each key is unique. Maps are used to store data in a structured way, making it easier to access and manipulate.
The Traditional Way of Iterating Maps
Before Java 8, iterating through maps required using iterators or loops. For example:
Mapmap = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); Iterator > iterator = map.entrySet().iterator(); while(iterator.hasNext()) { Map.Entry entry = iterator.next(); String key = entry.getKey(); String value = entry.getValue(); System.out.println(key + " =" + value); } for(Map.Entry entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); System.out.println(key + " =" + value); }
The Java 8 Way of Iterating Maps
Java 8 introduced the forEach() method, which can be used to iterate through maps. For example:
Mapmap = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.forEach((key, value) -> System.out.println(key + " =" + value));
The forEach() method takes a lambda expression as an argument, which is used to process each key-value pair in the map. The lambda expression has two parameters, key and value, which are used to access the key and value of each pair.
Filtering Maps in Java 8
Java 8 also introduced the filter() method, which can be used to filter maps based on certain criteria. For example:
Mapmap = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); Map filteredMap = map.entrySet().stream() .filter(entry -> "key1".equals(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); filteredMap.forEach((key, value) -> System.out.println(key + " =" + value));
The filter() method takes a predicate as an argument, which is used to filter the map based on certain criteria. In the example above, we filtered the map to only include the key-value pair where the key was “key1”.
Conclusion
Iterating through maps in Java 8 has become much easier and more efficient with the introduction of the forEach() and filter() methods. These methods make it simpler to process and manipulate data stored in maps, making Java 8 an even more powerful language for developers to use.