System.out.println(treeMap.firstEntry()); // Prints 1=oneSystem.out.println(treeMap.lastEntry()); // Prints 12=twelveSystem.out.println(treeMap.size()); // Prints 4, since there are 4 elemens in the mapSystem.out.println(treeMap.get(12)); // Prints twelveSystem.out.println(treeMap.get(15)); // Prints null, since the key is not found in the map
System.out.println(treeSet.first()); // Prints 1System.out.println(treeSet.last()); // Prints 12System.out.println(treeSet.size()); // Prints 4, since there are 4 elemens in the setSystem.out.println(treeSet.contains(12)); // Prints trueSystem.out.println(treeSet.contains(15)); // Prints false
Iteration
for (Integer i : treeSet) {System.out.print(i +" "); //prints 1 4 10 12}Iterator<Integer> iter =treeSet.iterator();while (iter.hasNext()) {System.out.print(iter.next() +" "); //prints 1 4 10 12}
TreeMap/TreeSet of a custom Java type
Since TreeMap and TreeSet s maintain keys/elements according to their natural ordering. Therefor TreeMap keys and TreeSet elements have to comparable to one another. you will run into the following error
Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to
java.lang.Comparable
One solution is to modify Object so it would implement the Comparable interface.
Another solution is to provide the TreeSet with a Comparator