1. What is TreeMap collection in java?
- Given a TreeMap collection containing key value pairs.
- TreeeMap is Red-Black tree based NavigableMap implementation.
- The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time
- Guaranteed time complexity log(n) for the containsKey, get, put and remove operations.
- Iterate or loop through the TreeMap using following methods.
- Iterate TreeMap collection of TreeMap<Integer,String> using entrySet iterator
- Iterate TreeMap collection of TreeMap<Integer,String> using forEach (java8)
- Once we accomplished the iteration process, the keys will be printed in sorted order.
2. Loop /iterate TreeMap collection of String objects in before & after java8
package org.learn.collection.map.tmap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; public class DemoTreeMap { public static void main(String[] args) { Map<Integer, String> mapVehicleNoAndOwner = new TreeMap<>(); mapVehicleNoAndOwner.put( 9000 , "Federer" ); mapVehicleNoAndOwner.put( 4000 , "Bradman" ); mapVehicleNoAndOwner.put( 7000 , "Jordan" ); mapVehicleNoAndOwner.put( 2000 , "Woods" ); mapVehicleNoAndOwner.put( 5000 , "Ali" ); System.out.println( "Method 1 - Iterate TreeMap: " ); demoIterateTreeMap(mapVehicleNoAndOwner); System.out.println( "\nMethod 2 - Iterate TreeMap using java 8: " ); demoIterateTreeMapJava8(mapVehicleNoAndOwner); } private static void demoIterateTreeMap(Map<Integer, String> mapVehicleNoAndOwner ) { for (Entry<Integer, String> entry : mapVehicleNoAndOwner .entrySet()) { Integer vehicleNumber = entry.getKey(); String owner = entry.getValue(); System.out.println( "Key:" + vehicleNumber + ", Value:" + owner); } } private static void demoIterateTreeMapJava8(Map<Integer, String> mapVehicleNoAndOwner) { mapVehicleNoAndOwner.forEach((key, value) -> { System.out.println( "Key:" + key + ", Value:" + value); }); } } |
3. Loop /iterate TreeMap collection of String objects in before & after java8
Method 1 - Iterate TreeMap: Key:2000, Value:Woods Key:4000, Value:Bradman Key:5000, Value:Ali Key:7000, Value:Jordan Key:9000, Value:Federer Method 2 - Iterate TreeMap using java 8: Key:2000, Value:Woods Key:4000, Value:Bradman Key:5000, Value:Ali Key:7000, Value:Jordan Key:9000, Value:Federer |