Explain Codes LogoExplain Codes Logo

How to iterate over a TreeMap?

java
iterator
lambda
generics
Anton ShumikhinbyAnton Shumikhin·Jan 2, 2025
TLDR

Peruse a TreeMap using its entrySet():

TreeMap<Integer, String> treeMap = new TreeMap<>(); // Assume the TreeMap is not shy - it's populated for (Map.Entry<Integer, String> entry : treeMap.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); }

This is straightforward and taps into the strength of the for-each loop.

Handling TreeMap with all its eccentricities

Up our sleeve, let’s lay out advanced iterations and savvy techniques to manipulate TreeMap entries. Our primary goal is to provide efficient, clean, and safe iterations.

Controlling iteration process using Iterators

For situations that need more "hands-on" control or to avoid ConcurrentModificationException, you can use Iterator:

Iterator<Map.Entry<String, Integer>> iterator = treeMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); // Doing something dangerous? No worries, you're in control! if (someCondition) { iterator.remove(); // Safe because we care } }

Lambda for the win!

With Java 8's Streams and lambda expressions, you can write expressive and short code. So why write more when you can write less:

// With lambda making our lives easier, forEach is our new best friend! treeMap.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));

Or to filter and collect entries:

TreeMap<Integer, String> filteredMap = treeMap.entrySet() .stream() .filter(e -> e.getValue().contains("some criteria")) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, TreeMap::new ));

Exceptions - We got them covered

Ensure robust code by handling exceptions while iterating:

try { treeMap.forEach((key, value) -> { if (key.equals(sensitiveKey)) { throw new SomeException(); // When keys give you headaches } }); } catch (SomeException ex) { // Catch them all, it's not a Pokémon game but equally fun! }

Google Collection magic for advanced filtering

Guava's Maps.filterKeys and Maps.filterEntries are excellent tools for filtering:

Predicate<String> isKeyValid = key -> key.startsWith("prefix"); Map<String, Integer> filteredMap = Maps.filterKeys(treeMap, isKeyValid); //Only the chosen ones shall pass!

Tackling TreeMap from all angles

Different data types

For complex keys and values, make sure you are using the right parameters:

TreeMap<CustomKey, CustomValue> customMap = new TreeMap<>(); // One TreeMap to rule them all! for (Map.Entry<CustomKey, CustomValue> entry : customMap.entrySet()) { // ... custom operations ... }

Key transformations

You can transform the keys while retaining the order:

TreeMap<NewKeyType, String> transformedMap = new TreeMap<>(); treeMap.forEach((key, value) -> { NewKeyType newKey = transformKeyFunction(key); //BOOM! You're a new key now! transformedMap.put(newKey, value); });

Type safety is key!

Ensure type safety by imposing Generics:

TreeMap<String, List<String>> genericMap = new TreeMap<>(); // Traverse with the might of Generics! for (Map.Entry<String, List<String>> entry : genericMap.entrySet()) { // ... operation on lists ... }