Class TreeMap
A 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, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the containsKey , get , put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest’s Introduction to Algorithms.
Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare ) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals ; it just fails to obey the general contract of the Map interface.
Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be «wrapped» using the Collections.synchronizedSortedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(. ));
The iterators returned by the iterator method of the collections returned by all of this class’s «collection view methods» are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
All Map.Entry pairs returned by methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method. (Note however that it is possible to change mappings in the associated map using put .)
This class is a member of the Java Collections Framework.
- Program: How to get all keys from TreeMap?
- List Of All TreeMap Sample Programs:
- About Author
- Most Visited Pages
- Get all keys from treemap in java
- Example
- Output
- Java TreeMap Tutorial with Examples
- How to create TreeMap objects?
- Java Print TreeMap Example
- How to print TreeMap in Java?
- 1. How to print all the keys of TreeMap?
- 2. How to print all the values of TreeMap?
- 3. How to print all the entries of TreeMap?
- 4. How to print TreeMap having custom class objects as keys or values?
Program: How to get all keys from TreeMap?
Below example shows how to get all keys from the given TreeMap. By using keySet() method, you can get all key entries as a Set object.
package com.java2novice.treemap; import java.util.Set; import java.util.TreeMap; public class MyTreeMapKeys < public static void main(String a[])< TreeMaphm = new TreeMap(); //add key-value pair to TreeMap hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third","THIRD INSERTED"); System.out.println(hm); Set keys = hm.keySet(); for(String key: keys) < System.out.println(key); >> >
List Of All TreeMap Sample Programs:
- Basic TreeMap Operations.
- How to iterate through TreeMap?
- How to copy Map content to another TreeMap?
- How to search a key in TreeMap?
- How to search a value in TreeMap?
- How to get all keys from TreeMap?
- How to get entry set from TreeMap?
- How to delete all elements from TreeMap?
- How to sort keys in TreeMap by using Comparator?
- How to sort keys in TreeMap by using Comparator with user define objects?
- How to get sorted sub-map from TreeMap?
- How to get first key element from TreeMap (Sorted Map)?
- How to get last key element from TreeMap (Sorted Map)?
- How to reverse sorted keys in a TreeMap?
Daemon thread is a low priority thread. It runs intermittently in the back ground, and takes care of the garbage collection operation for the java runtime system. By calling setDaemon() method is used to create a daemon thread.
About Author
I’m Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.
If you come across any mistakes or bugs, please email me to [email protected] .
Most Visited Pages
Get all keys from treemap in java
We can use keySet() method to get all keys from treemap in java.
keySet(): Returns a Set that contains the keys in this map. This method provides a set-view of the keys in this map.
Example
package com.w3spoint; import java.util.Set; import java.util.TreeMap; public class Test { public static void main(String args[]){ //Create TreeMap object. TreeMapInteger, String> treeMap = new TreeMapInteger, String>(); //Add objects to the TreeMap. treeMap.put(4, "Roxy"); treeMap.put(2, "Sunil"); treeMap.put(5, "Sandy"); treeMap.put(1, "Munish"); treeMap.put(3, "Pardeep"); //Print the TreeMap object. System.out.println("TreeMap elements:"); System.out.println(treeMap); SetInteger> keys = treeMap.keySet(); for(Integer key: keys){ System.out.println(key); } } }
package com.w3spoint; import java.util.Set; import java.util.TreeMap; public class Test < public static void main(String args[])< //Create TreeMap object. TreeMaptreeMap = new TreeMap(); //Add objects to the TreeMap. treeMap.put(4, "Roxy"); treeMap.put(2, "Sunil"); treeMap.put(5, "Sandy"); treeMap.put(1, "Munish"); treeMap.put(3, "Pardeep"); //Print the TreeMap object. System.out.println("TreeMap elements:"); System.out.println(treeMap); Set keys = treeMap.keySet(); for(Integer key: keys) < System.out.println(key); >> >
Output
TreeMap elements: {1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy} 1 2 3 4 5
Java TreeMap Tutorial with Examples
Java TreeMap tutorial with examples will help you understand how to use the Java TreeMap class in an easy way. TreeMap in Java is a tree based implementation of the Map interface. The TreeMap class implements the NavigableMap interface. Unlike the HashMap class, the keys of the TreeMap are sorted according to the natural ordering or by the custom comparator.
If you do not want the keys to be sorted by their natural ordering but by custom order, you can do so by providing the custom Comparator at the time of TreeMap creation using the below given constructor.
The TreeMap in Java provides log(n) time cost for get , put , remove and containsKey operations.
The TreeMap implementation is not synchronized. If multiple threads are trying to modify the TreeMap object simultaneously, then the access must be synchronized explicitly. You can either synchronize the TreeMap object or you can get the synchronized SortedMap object from the existing TreeMap using the synchronizedSortedMap method of the Collections class as given below.
The Iterator object obtained by the iterator method of the TreeMap is fail-fast. That means if the TreeMap object is structurally modified after obtaining the iterator (except by using iterator’s own remove method), calling any methods of the iterator object will throw ConcurrentModificationException .
How to create TreeMap objects?
The TreeMap class in Java provides several constructors to create the objects. The default constructor of the TreeMap class creates a new empty TreeMap object. The key-value pairs stored in this TreeMap object are stored by the natural ordering of its keys.
Java Print TreeMap Example
This example shows how to print TreeMap in Java. The example also shows how to print all keys, all values, and all entries of TreeMap using for loop and iterator.
How to print TreeMap in Java?
There are several ways using which you can print TreeMap keys, values and entries as given below.
1. How to print all the keys of TreeMap?
First, get all the keys of the TreeMap using the keySet method and then use the for loop to iterate and print them.
You can also use an Iterator as given below.
2. How to print all the values of TreeMap?
First, get all the values of the TreeMap using the values method and then use the for loop to iterate and print them.
You can also use an iterator as given below.
3. How to print all the entries of TreeMap?
Get all the entries of the TreeMap using the entrySet method and then use the for loop to iterate and print them.
You can also use an iterator as given below.
4. How to print TreeMap having custom class objects as keys or values?
Let’s first see an example of printing a TreeMap object having objects of a custom class Emp as values.
Well, it did not print any useful information at all. The reason is our Emp class has not overridden the toString method from the Object class. In that case, the toString method of the Object class is used which prints “[email protected]_hashcode” when an object is printed.
To fix this, we need to override the toString method in our Emp class. Let’s do that and try again.