Let’s learn iterate treemap in java.
iterate treemap in java
We cannot iterate TreeMap. Since TreeMap is not a collection. To iterate use entrySet() method of TreeMap class.
entrySet() method returns a Set view of the mappings contained in this map.
The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
import java.util.Map; import java.util.TreeMap; public class IterateTreeMap { public static void main(String[] args) { Map<String, String> tm = new TreeMap<String, String>(); tm.put("Audi", "Audi A8 L"); tm.put("BMW", "BMW 5 Series"); tm.put("Mercedes-Benz", "Mercedes-Benz V-Class"); tm.put("Bugatti", "Bugatti Chiron"); // using for-each loop iterate over TreeMap using entrySet() method for(Map.Entry<String, String> entry : tm.entrySet()) System.out.println("[" + entry.getKey() + ", " + entry.getValue() + "]"); } }
Output:
[Audi, Audi A8 L]
[BMW, BMW 5 Series]
[Bugatti, Bugatti Chiron]
[Mercedes-Benz, Mercedes-Benz V-Class]
Also read – variables in java