How to Get TreeMap Key or Value using Index in Java?
Last Updated :
23 Jul, 2021
The TreeMap in Java is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The TreeMap is sorted according to the natural ordering of its keys. The TreeMap class is a Red-Black tree implementation of the Map interface and thus does not expose any methods using which we can access the TreeMap keys or values using their indices.
There are three simple ways to get key or TreeMap value using index in Java, which is the following :
- Using an Array
- Using a List
- Using iteration
Method 1: Using an Array
We can get a TreeMap key or TreeMap value using an index in Java by using an Array. The process is divided into three steps:
- Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object.
- Convert the entry set to an array using the toArray() method.
- And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method
Syntax:
Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet();
Map.Entry<Integer, String>[] entryArray = entrySet.toArray(new Map.Entry[entrySet.size()]);
Example:
Java
// Java Program to get TreeMap key or TreeMap value
// using index
// Importing all classes of
// java.util package
import java.util.*;
// Class
public class GFG {
// MAin driver method
public static void main(String[] args)
{
// Creating a New TreeMap
TreeMap<Integer, String> treeMap
= new TreeMap<Integer, String>();
// Add elements to TreeMap
// Custom inputs
treeMap.put(1, "Welcome");
treeMap.put(2, "geeks");
treeMap.put(3, "on");
treeMap.put(4, "geeksforgeeks");
// Get entry set of the TreeMap using entrySet
// method
Set<Map.Entry<Integer, String> > entrySet
= treeMap.entrySet();
// Convert entrySet to Array using toArray method
Map.Entry<Integer, String>[] entryArray
= entrySet.toArray(
new Map.Entry[entrySet.size()]);
// For loop for iteration and printing
for (int i = 0; i < 4; i++)
{
// Get Key using index and print
System.out.println("Key at " + i + ":"
+ entryArray[i].getKey());
// Get value using index and print
System.out.println("Value at " + i + ":"
+ entryArray[i].getValue());
}
}
}
Output:
1
Welcome
2
geeks
3
on
4
geeksforgeeks
Method 2: Using a List
We can get TreeMap key or TreeMap value using index in Java by using a List instead of Array. The process is divided into three steps:
- Using entrySet() method of the TreeMap class to get a set view of all the entries stored in the TreeMap object.
- Now, converting the entry set to an array using the toArray() method.
- Finally, getting TreeMap key or TreeMap value using index with the help of get(), getKey() and getValue() methods.
Syntax:
Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet();
List<Map.Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(entrySet);
Example:
Java
// Java Program to get TreeMap key or TreeMap value
// using index
// Importing all classes of
// java.util package
import java.util.*;
// Class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a TreeMap
TreeMap<Integer, String> treeMap = new TreeMap<>();
// Add elements to TreeMap
// Custom inputs
treeMap.put(1, "Welcome");
treeMap.put(2, "geeks");
treeMap.put(3, "on");
treeMap.put(4, "geeksforgeeks");
// Get entry set of the TreeMap
// using entrySet method
Set<Map.Entry<Integer, String> > entrySet
= treeMap.entrySet();
// Converting entrySet to ArrayList
List<Map.Entry<Integer, String> > entryList
= new ArrayList<>(entrySet);
// For each loop for iteration
for (int i = 0; i < 4; i++) {
// Print Key and Values using index
// Get Key using index
System.out.println("Key at " + i + ":"
+ entryList.get(i).getKey());
// Get value using index
System.out.println(
"Value at " + i + ":"
+ entryList.get(i).getValue());
}
}
}
OutputKey at 0:1
Value at 0:Welcome
Key at 1:2
Value at 1:geeks
Key at 2:3
Value at 2:on
Key at 3:4
Value at 3:geeksforgeeks
Method 3: Using iteration
We can get TreeMap key or TreeMap value using index in Java by using an iteration. The process is divided into two steps:
- Using the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object.
- Iterating on entrySet to get TreeMap key or TreeMap value using index with the help of getKey() and getValue() methods.
Syntax:
Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet();
Example:
Java
// Java Program to get TreeMap key or TreeMap value using
// index
// Importing all classes of
// java.util package
import java.util.*;
// Class
public class GFG {
// MAin driver method
public static void main(String[] args)
{
// Creating a TreeMp
TreeMap<Integer, String> treeMap = new TreeMap<>();
// Add elements to TreeMap
// Custom inputs
treeMap.put(1, "Welcome");
treeMap.put(2, "geeks");
treeMap.put(3, "on");
treeMap.put(4, "geeksforgeeks");
// Get entry set of the TreeMap
// using entrySet method
Set<Map.Entry<Integer, String> > entrySet
= treeMap.entrySet();
int index = 0;
// For-each loop for iteration
for (Map.Entry<Integer, String> currentEntry :
entrySet) {
// Print Key and Values using index
// Get Key using index
System.out.println("Key at " + index + ":"
+ currentEntry.getKey());
// Get value using index
System.out.println("Value at " + index + ":"
+ currentEntry.getValue());
index++;
}
}
}
OutputKey at 0:1
Value at 0:Welcome
Key at 1:2
Value at 1:geeks
Key at 2:3
Value at 2:on
Key at 3:4
Value at 3:geeksforgeeks
Similar Reads
How to Sort a TreeMap By Value in Java?
In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys. Sorting TreeMap by value in Java The elements in TreeMap are sorted on the basis of
3 min read
How to Create a TreeMap in Java and Add Key-Value Pairs in it?
In Java, a TreeMap maintains elements in a sorted order as it is an implementation of the SortedMap Interface. It stores key-value pairs in a sorted order. In this article, we will explore the creation of TreeMap in Java and learn the step-by-step process of adding key-value pairs. Program to Create
2 min read
How to Get a Value From LinkedHashMap by Index in Java?
LinkedHashMap is a predefined class in Java which is similar to HashMap, contain key and its respective value unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to get value from LinkedHashMap by their Index in other words, an order of their insertion. As an advantage of Link
4 min read
How to Copy Key-Value Pairs from One TreeMap to Another in Java?
In Java, a TreeMap is a Map implementation that stores key-value pairs in a red-black tree structure. It allows insertions and deletions of key-value pairs due to its tree implementation. These operations take O(log n) time on average. In this article, we will be learning how to copy key-value pairs
2 min read
How to Create TreeMap Objects using Comparable Interface in Java?
In Java, the TreeMap class is an implementation of the SortedMap interface that stores key-value pairs in a sorted order based on the natural ordering of the keys. By default, the keys are sorted in ascending order. If you want to sort the keys based on a custom ordering criteria, you can use the Co
6 min read
How to Merge Two TreeMaps in Java?
In Java, TreeMap is a pre-defined class that implements the NavigableMap interface and extends the AbstractMap class. In this article, we will learn to Merge Two Tree Maps in Java. Program to Merge Two TreeMaps in JavaWe are using the putAll method is inherited from the AbstractMap class in this man
2 min read
How to Implement a Cache Eviction Policy using TreeMap in Java?
To enhance application speed, caching is a method that stores frequently visited data in memory. When the cache fills up, a cache eviction policy decides which things must be removed. A sorted map implementation is provided by Java's TreeMap, which may be used to create a cache with a unique evictio
3 min read
How to Update the Value for an Existing Key in a TreeMap Using put()?
TreeMap is a part of Java Collection that can in-built class of java.util package. In Java, TreeMap is a pre-defined class that implements the NavigableMap interface and extends the AbstractMap class. It represents the Key-Value pairs. It is part of the Java Collection Framework.It is a sorted map b
2 min read
How to Replace a Value for the Given Key in the TreeMap?
The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. 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. It is the implementation class of Map i
4 min read
How to Get All the Values of the LinkedHashMap in Java?
LinkedHashMap is a predefined class in Java that is similar to HashMap, contains key and its respective value, unlike HashMap. In LinkedHashMap insertion order is preserved. The task is to get all the values present in our LinkedHashMap that is linked with their respective key. Use Iteration or pred
4 min read