0% found this document useful (0 votes)
4 views

Java TreeMap

Uploaded by

anandbinde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java TreeMap

Uploaded by

anandbinde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

28/11/2024, 12:46 Java TreeMap

Tutorials Interview Compiler

Home Python Java JavaScript HTML SQL PHP C# C++ DS Aptitude

← prev next →
Java Collections

Collection Framework

Java ArrayList

Java LinkedList

ArrayList vs LinkedList

Java List Interface Java TreeMap Class


Java HashSet Java TreeMap class is a red-black tree-based implementation. It provides
an efficient means of storing key-value pairs in sorted order.
Java LinkedHashSet

Java TreeSet The java.util package contains the Java TreeMap class, which is a
component of the Java Collections Framework. It extends the
Queue & PriorityQueue
AbstractMap class and implements the NavigableMap interface. TreeMap
Deque & ArrayDeque is an effective red-black tree-based solution that sorts key-value pairs.
Java Map Interface TreeMap works well in situations where ordered key-value pairs are
necessary since it preserves ascending order. It also only includes distinct
Java HashMap
components, guaranteeing that every key corresponds to a single value.
Working of HashMap
TreeMap can have more than one null value, even if it cannot have a null
Java LinkedHashMap key.
https://www.javatpoint.com/java-treemap 1/26
28/11/2024, 12:46 Java TreeMap

Java TreeMap

Java Hashtable

HashMap vs Hashtable

Java EnumSet

Java EnumMap

Collections class

Sorting Collections

Comparable interface

Comparator interface The important points about Java TreeMap class are:

Comparable vs Comparator
Java TreeMap contains values based on the key. It implements
Properties class the NavigableMap interface and extends AbstractMap class.
ArrayList vs Vector
Java TreeMap contains only unique elements.
Java Vector
Java TreeMap cannot have a null key but can have multiple null
Java Stack values.
Java Collection Interface
Java TreeMap is non synchronized.
Java Iterator Interface
Java TreeMap maintains ascending order.
Java Deque Interface

Java ConcurrentHashMap
TreeMap Class Declaration
Collection Quiz-1
Let's see the declaration for java.util.TreeMap class.

https://www.javatpoint.com/java-treemap 2/26
28/11/2024, 12:46 Java TreeMap

Java
ConcurrentHashMap

Java ConcurrentHashMap
hashcode() Method

Java ConcurrentHashMap
clear() Method

Java ConcurrentHashMap
computeIfAbsent() Method

Java ConcurrentHashMap
computeIfPresent() Method
public class TreeMap<k ,v> extends AbstractMap<k ,v> implement
Java ConcurrentHashMap s NavigableMap<k ,v>, Cloneable, Serializable
compute() Method
</k></k></k>
Java ConcurrentHashMap
containsKey() Method

Java ConcurrentHashMap TreeMap Class Parameters


contains() Method
Let's see the Parameters for java.util.TreeMap class.
Java ConcurrentHashMap
containsValue() Method K: It is the type of keys maintained by this map.
Java ConcurrentHashMap
elements() Method
V: It is the type of mapped values.

Java ConcurrentHashMap
entrySet() Method

Java ConcurrentHashMap Constructors of Java TreeMap class


equals() Method

https://www.javatpoint.com/java-treemap 3/26
28/11/2024, 12:46 Java TreeMap

Java ConcurrentHashMap Constructor Description


forEach() Method

Java ConcurrentHashMap get() TreeMap() It is used to construct an empty


Method tree map that will be sorted
Java ConcurrentHashMap using the natural order of its key.
getOrDefault() Method
TreeMap(Comparator<? super It is used to construct an empty
Java ConcurrentHashMap
K> comparator) tree-based map that will be
keySet() Method
sorted using the comparator
Java ConcurrentHashMap keys() comp.
Method

Java ConcurrentHashMap TreeMap(Map<? extends K,? It is used to initialize a TreeMap


mappingCount() Method extends V> m) with the entries from m, which
Java ConcurrentHashMap will be sorted using the natural
merge() Method order of the keys.
Java ConcurrentHashMap TreeMap(SortedMap<K,? It is used to initialize a TreeMap
newKeySet() Method
extends V> m) with the entries from the
Java ConcurrentHashMap SortedMap sm, which will be
putAll() Method
sorted in the same order as sm.
Java ConcurrentHashMap
putIfAbsent() Method TreeMap(Collection<? extends It constructs a tree map
K> c) containing the elements of the
Java ConcurrentHashMap put()
Method specified collection, sorted
using their natural order.
Java ConcurrentHashMap
remove() Method
TreeMap(SortedMap<K, ? It initializes a TreeMap with the
Java ConcurrentHashMap extends V> m, Comparator<? entries from the provided sorted
replace() Method super K> comparator)
https://www.javatpoint.com/java-treemap 4/26
28/11/2024, 12:46 Java TreeMap

Java ConcurrentHashMap map and uses the given


toString() Method comparator for sorting.
Java ConcurrentHashMap
values() Method
Methods of Java TreeMap Class

Method Description
Java
ConcurrentLinkedQueue Map.Entry<K,V> ceilingEntry(K It returns the key-value pair
key) having the least key, greater
Java ConcurrentLinkedQueue
than or equal to the specified
key, or null if there is no such
Java ConcurrentLinkedQueue
key.
toArray() Method

Java ConcurrentLinkedQueue K ceilingKey(K key) It returns the least key, greater


spliterator() Method than the specified key or null if
Java ConcurrentLinkedQueue there is no such key.
size() method
void clear() It removes all the key-value pairs
Java ConcurrentLinkedQueue
from a map.
retainAll() method

Java ConcurrentLinkedQueue Object clone() It returns a shallow copy of


remove() Method TreeMap instance.
Java ConcurrentLinkedQueue
removeIf() Method Comparator<? super K> It returns the comparator that
comparator() arranges the key in order, or null
Java ConcurrentLinkedQueue
if the map uses the natural
removeAll() Method
ordering.
Java ConcurrentLinkedQueue
offer() Method
https://www.javatpoint.com/java-treemap 5/26
28/11/2024, 12:46 Java TreeMap

Java ConcurrentLinkedQueue NavigableSet<K> It returns a reverse order


iterator() Method
descendingKeySet() NavigableSet view of the keys
Java ConcurrentLinkedQueue contained in the map.
isEmpty() Method

Java ConcurrentLinkedQueue NavigableMap<K,V> It returns the specified key-value


forEach() Method descendingMap() pairs in descending order.
Java ConcurrentLinkedQueue Map.EntryfirstEntry() It returns the key-value pair
contains() Method
having the least key.
Java ConcurrentLinkedQueue
add() method Map.Entry<K,V> floorEntry(K It returns the greatest key, less
Java ConcurrentLinkedQueue key) than or equal to the specified
addAll() method key, or null if there is no such
key.

void forEach(BiConsumer<? It performs the given action for


super K,? super V> action) each entry in the map until all
entries have been processed or
the action throws an exception.

SortedMap<K,V> headMap(K It returns the key-value pairs


toKey) whose keys are strictly less than
toKey.

NavigableMap<K,V> headMap(K It returns the key-value pairs


toKey, boolean inclusive) whose keys are less than (or
equal to if inclusive is true)
toKey.

https://www.javatpoint.com/java-treemap 6/26
28/11/2024, 12:46 Java TreeMap

Map.Entry<K,V> higherEntry(K It returns the least key strictly


key) greater than the given key, or
null if there is no such key.

K higherKey(K key) It is used to return true if this


map contains a mapping for the
specified key.

SetkeySet() It returns the collection of keys


exist in the map.

Map.Entry<K,V> lastEntry() It returns the key-value pair


having the greatest key, or null if
there is no such key.

Map.Entry<K,V> lowerEntry(K It returns a key-value mapping


key) associated with the greatest key
strictly less than the given key,
or null if there is no such key.

K lowerKey(K key) It returns the greatest key


strictly less than the given key,
or null if there is no such key.

NavigableSet<K> It returns a NavigableSet view of


navigableKeySet() the keys contained in this map.

Map.Entry<K,V> pollFirstEntry() It removes and returns a key-


value mapping associated with
https://www.javatpoint.com/java-treemap 7/26
28/11/2024, 12:46 Java TreeMap

the least key in this map, or null


if the map is empty.

Map.Entry<K,V> pollLastEntry() It removes and returns a key-


value mapping associated with
the greatest key in this map, or
null if the map is empty.

V put(K key, V value) It inserts the specified value


with the specified key in the
map.

void putAll(Map<? extends K,? It is used to copy all the key-


extends V> map) value pair from one map to
another map.

V replace(K key, V value) It replaces the specified value


for a specified key.

boolean replace(K key, V It replaces the old value with the


oldValue, V newValue) new value for a specified key.

void replaceAll(BiFunction<? It replaces each entry's value


super K,? super V,? extends V> with the result of invoking the
function) given function on that entry
until all entries have been
processed or the function
throws an exception.

https://www.javatpoint.com/java-treemap 8/26
28/11/2024, 12:46 Java TreeMap

NavigableMap<K,V> subMap(K It returns key-value pairs whose


fromKey, boolean fromInclusive, keys range from fromKey to
K toKey, boolean toInclusive) toKey.

SortedMap<K,V> subMap(K It returns key-value pairs whose


fromKey, K toKey) keys range from fromKey,
inclusive, to toKey, exclusive.

SortedMap<K,V> tailMap(K It returns key-value pairs whose


fromKey) keys are greater than or equal to
fromKey.

NavigableMap<K,V> tailMap(K It returns key-value pairs whose


fromKey, boolean inclusive) keys are greater than (or equal
to, if inclusive is true) fromKey.

boolean containsKey(Object It returns true if the map


key) contains a mapping for the
specified key.

boolean containsValue(Object It returns true if the map maps


value) one or more keys to the
specified value.

K firstKey() It is used to return the first


(lowest) key currently in this
sorted map.

https://www.javatpoint.com/java-treemap 9/26
28/11/2024, 12:46 Java TreeMap

V get(Object key) It is used to return the value to


which the map maps the
specified key.

K lastKey() It is used to return the last


(highest) key currently in the
sorted map.

V remove(Object key) It removes the key-value pair of


the specified key from the map.

Set<Map.Entry<K,V>> entrySet() It returns a set view of the


mappings contained in the
map.

int size() It returns the number of key-


value pairs exists in the
hashtable.

Collectionvalues() It returns a collection view of the


values contained in the map.

Java TreeMap Example


File Name: TreeMap1.java

import java.util.*;
class TreeMap1{
https://www.javatpoint.com/java-treemap 10/26
28/11/2024, 12:46 Java TreeMap

public static void main(String args[]){


TreeMap<integer ,string> map=new TreeMap<integer ,string>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");

for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
</integer></integer>

Output:

100 Amit
101 Vijay
102 Ravi
103 Rahul

Explanation

This Java code illustrates how to store key-value pairs and loop through
the elements of a TreeMap class. Initially, the java.util.* package is
imported in order to use the TreeMap class and other associated utilities.

https://www.javatpoint.com/java-treemap 11/26
28/11/2024, 12:46 Java TreeMap

Next, a TreeMap instance map with integer keys and string values is
generated within the TreeMap1 class. Using the put() method, four key-
value pairs are added to the TreeMap. Every entry comprises a string value
that corresponds to an integer key.

The entrySet() method, which yields a set representation of the mappings


in the map, is then used by a for-each loop to iterate over the entries of the
TreeMap. Inside the loop, each entry is accessed using the getKey() and
getValue() methods of the Map.Entry interface, and its key-value pair is
printed to the console.

Java TreeMap Example: remove()


File Name: TreeMap2.java

import java.util.*;
https://www.javatpoint.com/java-treemap 12/26
28/11/2024, 12:46 Java TreeMap

public class TreeMap2 {


public static void main(String args[]) {
TreeMap<integer ,string> map=new TreeMap<integer ,string>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Before invoking remove() method");
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
map.remove(102);
System.out.println("After invoking remove() method");
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
</integer></integer>

Output:

Before invoking remove() method


100 Amit

https://www.javatpoint.com/java-treemap 13/26
28/11/2024, 12:46 Java TreeMap

101 Vijay
102 Ravi
103 Rahul
After invoking remove() method
100 Amit
101 Vijay
103 Rahul

Explanation

The Java code that is provided shows how to remove an entry using the
remove() method and stores key-value pairs using the TreeMap class. The
TreeMap is first updated with key-value pairs, which link integer keys to
matching string values.

Then, before and after using the remove() method to remove an entry
with the key 102, the contents of the TreeMap are reported. This is a brief
code piece that demonstrates the basic capability of adding, removing,
and iterating over entries in a TreeMap, highlighting its ordered and
mutable properties.

Java TreeMap Example: NavigableMap


File Name: TreeMap3.java

import java.util.*;
class TreeMap3{
public static void main(String args[]){
https://www.javatpoint.com/java-treemap 14/26
28/11/2024, 12:46 Java TreeMap

NavigableMap<integer ,string> map=new TreeMap<integer ,strin


g>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//Maintains descending order
System.out.println("descendingMap: "+map.descendingMap());
//Returns key-
value pairs whose keys are less than or equal to the specified key.
System.out.println("headMap: "+map.headMap(102,true));
//Returns key-
value pairs whose keys are greater than or equal to the specified ke
y.
System.out.println("tailMap: "+map.tailMap(102,true));
//Returns key-value pairs exists in between the specified key.
System.out.println("subMap: "+map.subMap(100, false, 102, true)
);
}
}

</integer></integer>

Output:

https://www.javatpoint.com/java-treemap 15/26
28/11/2024, 12:46 Java TreeMap

descendingMap: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}


headMap: {100=Amit, 101=Vijay, 102=Ravi}
tailMap: {102=Ravi, 103=Rahul}
subMap: {101=Vijay, 102=Ravi}

Explanation

This Java code creates a map that retains key-value pairs in ascending
order according to the keys by using the TreeMap class and the
NavigableMap interface. Following the addition of integer keys and
associated string values to the TreeMap, the code illustrates the several
navigation functions offered by the NavigableMap interface.

In addition to displaying methods like headMap(), tailMap(), and subMap()


that obtain subsets of the map based on specified key ranges, it publishes
the descending map, which reverses the order of the key-value pairs.
These procedures demonstrate the adaptability and features that

https://www.javatpoint.com/java-treemap 16/26
28/11/2024, 12:46 Java TreeMap

TreeMap provides for categorising and retrieving key-value pairs based on


various standards.

Java TreeMap Example: SortedMap

import java.util.*;
class TreeMap4{
public static void main(String args[]){
SortedMap<integer ,string> map=new TreeMap<integer ,string>
();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//Returns key-
value pairs whose keys are less than the specified key.
https://www.javatpoint.com/java-treemap 17/26
28/11/2024, 12:46 Java TreeMap

System.out.println("headMap: "+map.headMap(102));
//Returns key-
value pairs whose keys are greater than or equal to the specified ke
y.
System.out.println("tailMap: "+map.tailMap(102));
//Returns key-value pairs exists in between the specified key.
System.out.println("subMap: "+map.subMap(100, 102));
}
}

</integer></integer>

Output:

headMap: {100=Amit, 101=Vijay}


tailMap: {102=Ravi, 103=Rahul}
subMap: {100=Amit, 101=Vijay}

Explanation

https://www.javatpoint.com/java-treemap 18/26
28/11/2024, 12:46 Java TreeMap

The SortedMap interface and TreeMap class are used in this Java code to
construct a sorted map whose key-value pairs are arranged according to
the keys' natural ordering, which in this case is integers. The code uses
methods given by the SortedMap interface to obtain subsets of the map
based on specified key ranges after initialising the TreeMap with integer
keys and matching string values.

It highlights the headMap(), tailMap(), and subMap() functions in


particular, which return key-value pairs whose keys are, respectively, less
than, greater than, or equal to, and exist between the given keys. These
actions demonstrate how effectively TreeMap can handle and retrieve key-
value pairs in the order in which they are sorted.

What is difference between HashMap and TreeMap?

HashMap TreeMap

HashMap does not guarantee a TreeMap guarantees a sorted


sorted order of elements. order of elements based on the
natural ordering of keys or a
custom comparator.

https://www.javatpoint.com/java-treemap 19/26
28/11/2024, 12:46 Java TreeMap

HashMap is generally faster for TreeMap offers efficient range


insertion and retrieval queries and operations like
operations, especially for large finding the closest key.
datasets.

HashMap uses hashing for TreeMap uses a red-black tree


storing key-value pairs, internally, resulting in
providing constant-time logarithmic-time complexity for
performance for basic most operations, making it
operations (e.g., get, put, slightly slower than HashMap
remove) on average. for basic operations.

Iterating over elements in a Iterating over elements in a


HashMap does not guarantee TreeMap results in sorted order
any specific order. based on the keys.

HashMap allows null values, and TreeMap allows null values but
multiple null values can be not null keys.
associated with different keys.

HashMap is not synchronized, TreeMap is not synchronized,


making it not thread-safe. making it not thread-safe.

HashMap is part of the java.util TreeMap is part of the java.util


package. package and implements the
NavigableMap interface.

Java TreeMap Example: Book


https://www.javatpoint.com/java-treemap 20/26
28/11/2024, 12:46 Java TreeMap

File Name: MapExample.java

import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int
quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class MapExample {
public static void main(String[] args) {
//Creating map of Books
Map<integer ,book> map=new TreeMap<integer ,book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Fo
rouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
map.put(2,b2);
https://www.javatpoint.com/java-treemap 21/26
28/11/2024, 12:46 Java TreeMap

map.put(1,b1);
map.put(3,b3);

//Traversing map
for(Map.Entry<integer , book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher
+" "+b.quantity);
}
}
}
</integer></integer></integer>

Output:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6

Explanation

https://www.javatpoint.com/java-treemap 22/26
28/11/2024, 12:46 Java TreeMap

This Java code illustrates how to store and retrieve objects of a custom
class called Book using a TreeMap. Initially, the Book class is defined with a
constructor to initialise the attributes id, name, author, publisher, and
quantity.

A TreeMap instance called "map" is constructed with integer keys and


Book objects as values in the MapExample class's main function. Using
their respective ids as keys, three Book objects are constructed and added
to the TreeMap. The key and associated Book object are then extracted by
the code as iteratively goes over the TreeMap elements using a for-each
loop.

Next Topic Java Hashtable class

https://www.javatpoint.com/java-treemap 23/26
28/11/2024, 12:46 Java TreeMap

← prev next →

Latest Courses  

https://www.javatpoint.com/java-treemap 24/26
28/11/2024, 12:46 Java TreeMap

https://www.javatpoint.com/java-treemap 25/26
28/11/2024, 12:46 Java TreeMap

https://www.javatpoint.com/java-treemap 26/26

You might also like