TreeMap basics

With TreeMaps, unlike HashMaps, the elements are already arranged in a specific order.

Syntax

import java.util.TreeMap;

TreeMap<Integer, String> map = new TreeMap<Integer, String>();

Example TreeMap

import java.util.TreeMap;

public class TreeMapExample {
	public static void main(String[] args) {
		TreeMap<Integer, String> map = new TreeMap<Integer, String>();
		map.put(10, "productA");
		map.put(24, "productB");
		map.put(3, "productC");
		map.put(8, "productD");
        map.put(44, "productF");
		
		for(Integer key: map.keySet()) {
			System.out.println(key + ": " + map.get(key));
		}

        // Returns a Collection view of the values contained in this map.
        System.out.println(map.values());
        // Returns a Set view of the keys contained in this map.
        System.out.println(map.keySet());
	}
}
Output
3: productC
8: productD
10: productA
24: productB
44: productF
[productC, productD, productA, productB, productF]
[3, 8, 10, 24, 44]