Java TreeMap Tutorial
with Examples
Hello Readers in this article we are going to see Java TreeMap with Examples,so
let's begin.
Java TreeMap is Red-Black tree
based implementation of Map Interface.
It stores the elements
in key value pairs and sort in natural sorting order based on its keys,however
we can sort TreeMap according to our requirement with custom
sorting(Using Comparator).
TreeMap class implements
Map using tree structure.
Note:TreeMap implements NavigableMap interface,so it has the functionalities of both the NavigableMap as well as SortedMap.
SortedMap interface provide the functionalities to maintain the
sorting order of keys,and NavigableMap interface
provides functionalities to navigate the Map,For example,finding the last
flight before 4 o-clock and first flight after 4 o-clock,finding the first and
last entries from TreeMap etc.
Points need to be
remembered about TreeMap.
1.
A TreeMap is sorted based on keys.
2.
The sorting order is
based on natural sorting of keys.
3.
We may also provide a
custom sorting order by passing custom Comparator to the TreeMap at the time of creation,depend on which constructor we are
using.
4.
A TreeMap can not contain duplicate keys,as keys are comparable.
5.
A TreeMap can not contain null
keys as objects adding as key should be Comparable and null is not an object.
6.
But TreeMap can have null values.
7.
TreeMap is not synchronized.
TreeMap Class
Declaration.
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>,
Cloneable, java.io.Serializable
Constructor of TreeMap
Class
TreeMap()
It is used to construct
an empty TreeMap that will be sorted on natural sorting order.
TreeMap(Comparator c)
It is used to construct
an empty TreeMap that will be sorted using the Comparator c.
TreeMap(Map map)
It is used to initialize
a TreeMap with entries from map with natural sorting order.
TreeMap(SortedMap
sormap)
It is used to initialize
a TreeMap with entries from sormap with same sorting order as sormap.
Methods.
public int size();
It is used to return the
size of TreeMap.
public boolean
containsKey(Object key);
Returns true if this map
contains one or more keys to the specified .
key.
public boolean
containsValue(Object value);
Returns true if this map
contains one or more value to the specified value.
get(Object key);
It is used to return the
value of specified key.
Object firstKey();
It is used to get first
key of this TreeMap.
Object lastKey();
It is used to get last
key of this TreeMap.
void putAll(Map m);
It is used to add given
map to this map.
Set entrySet();
it is used to return a
Set of entries(key,value) of this map.
Set keySet();
it is used to return a
Set of keys of this map.
Collection values();
it is used to return a
values of this map.
A Simple TreeMap
Example
File Name:TreeMapDemoDefaultSorting.java
1. import java.util.*;
2. public class TreeMapDemoDefaultSorting{
3. public static void main(String[] args) {
5. TreeMap
m=new TreeMap();
6. m.put(1,
"one");
7. m.put(4,
"four");
8. m.put(3,
"three");
9. m.put(2,
"two");
10. System.out.println("Normal TreeMap "+m);
11. }//end of main
12. }//end of class
output:
Normal TreeMap {1=one,
2=two, 3=three, 4=four}
Iterating Over TreeMap
File Name:TreeMapIterationDemo.java
1. import java.util.*;
2. import java.util.Map.Entry;
3. public class TreeMapIterationDemo{
4. public static void main(String[] args) {
5. TreeMap<Integer,String>
m=new
TreeMap<Integer,String>();
6. m.put(1,
"one");
7. m.put(4,
"four");
8. m.put(3,
"three");
9. m.put(2,
"two");
10. System.out.println("Getting Entries One By One");
11. for(Map.Entry<Integer, String>
me:m.entrySet()){
12. System.out.println(me.getKey()+" "+me.getValue());
13. }
14. System.out.println("Another Way To Iterate Over TreeMap");
15. Set<Map.Entry<Integer,String>>
myEnterSet=m.entrySet();
16. Iterator<Entry<Integer,
String>> itr=myEnterSet.iterator();
17. while(itr.hasNext())
18. {
19. Entry<Integer,
String> e=itr.next();
20. System.out.println(e.getKey()+" "+e.getValue());
21. }//end of
while
22. }//end of main
23. }//end of class
output:
Getting Entries One By
One
1 one
2 two
3 three
4 four
Another Way To Iterate
Over TreeMap
1 one
2 two
3 three
4 four
Use Of Methods
File Name:UseOfMethods.java
In this example we have
used several methods to demonstrate the working of all these methods.
1.
import java.util.*;
2. import java.util.Map.Entry;
3. public class UseOfMethods{
4. public static void main(String[] args) {
5. TreeMap<Integer,String> m=new
TreeMap<Integer,String>();
6. m.put(1, "one");
7. m.put(4, "four");
8. m.put(3, "three");
9. m.put(2, "two");
10. System.out.println("Use
of Size "+m.size());
11. System.out.println("Use
of containsKey "+m.containsKey(3)+" "+m.containsKey(5));
12. System.out.println("Use
of containsValue "+m.containsValue("one")+"
"+m.containsValue("ten"));
13.
System.out.println("Use
of get(1) "+m.get(1));
14.
System.out.println("Use
of firstKey() "+m.firstKey());
15.
System.out.println("Use
of lasstKey() "+m.lastKey());
16.
17.
TreeMap<Integer,String>
m1=new TreeMap<Integer,String>();
18.
m.put(5,
"five");
19.
m.put(6,
"six");
20.
m.put(7,
"seven");
21.
m.put(8,
"eight");
22.
m.putAll(m1);
23.
24.
System.out.println("m
After m.putAll(m1) "+m);
25.
System.out.println("use
of keySet() "+m.keySet());
26.
System.out.println("use
of values() "+m.values());
27.
28.
System.out.println("Use
of enteySet() ");
29.
//enteySet() returns
the set of entries
30.
//so we can iterate
over them to get entries one by one see example
31.
Set<Map.Entry<Integer,String>>
myEnterSet=m.entrySet();
32.
Iterator<Entry<Integer,
String>> itr=myEnterSet.iterator();
33.
while(itr.hasNext()){
34.
Entry<Integer,
String> e=itr.next();
35.
System.out.println(e.getKey()+"
"+e.getValue());
36.
}//end of while
37.
}//end of main
38.
}//end of class
output:
Use of Size 4
Use of containsKey true false
Use of containsValue true false
Use of get(1) one
Use of firstKey() 1
Use of lasstKey() 4
m After m.putAll(m1) {1=one, 2=two, 3=three, 4=four, 5=five, 6=six,
7=seven, 8=eight}
use of keySet() [1, 2, 3, 4, 5, 6, 7, 8]
use of values() [one, two, three, four, five, six, seven, eight]
Use of enteySet()
1 one
2 two
3 three
4 four
5 five
6 six
7 seven
8 eight
TreeMap Example To
Check Users Credential.
Create a class with main
method.
Create TreeMap object
and put some credentials i.e.,Key and value of String types(in this case String).
TreeMap<String,String> credentials=new
TreeMap<String,String>();
Here in this example i
have putted some keys with values, see example.
1. credentials.put("Mateen1","12341");
2. credentials.put("Mateen2","12342");
3. credentials.put("Mateen3","12343");
4. System.out.println("Normal TreeMap : "+credentials);
4. System.out.println("Normal TreeMap : "+credentials);
Output : Normal TreeMap : {Mateen1=12341, Mateen2=12342, Mateen3=12343} ok.
-Now we are taking input
from the user in this case username and password as String using BufferedReader.
1. BufferedReader readCre=new BufferedReader(new
InputStreamReader(System.in));
2. System.out.println("Enter
Username");
3. String user=readCre.readLine();
4. System.out.println("Enter
Password");
5. String pass=readCre.readLine();
After all these necessary steps we are writing credentials checking logic i.e., username and password,if this Map contains given entryset then user is valid user otherwise invalid user,see example.
File name:Login.java
package com.Acton;
import java.io.*;
import java.util.*;
public class Login{
public static void main(String[] args) throws IOException {
TreeMap<String,String>
credentials=new TreeMap<String,String> ();
credentials.put("Mateen1","12341");
credentials.put("Mateen2","12342");
credentials.put("Mateen3","12343");
System.out.println("Noraml TreeMap : "+credentials);
//login logic
BufferedReader readCre=new BufferedReader(new InputStreamReader(System.in));
String choice=null;
boolean flag=true;
while(flag)
{
System.out.println("Enter Username");
String user=readCre.readLine();
System.out.println("Enter Password");
String pass=readCre.readLine();
if(credentials.containsKey(user))
{
String p=credentials.get(user);
if(pass.equalsIgnoreCase(p))
{
System.out.println("Welcome "+user );
break;
}//end of 2nd
if
else
{
System.err.println("Invalid Password");
System.out.println("Do you want to try again? press y to try again");
choice=readCre.readLine();
if(!(choice.startsWith("y")))
{
flag=false;
}
}//end of 2nd
else
}//end of 1st if
else {
System.err.println("Invalid User");
System.out.println("Do you want to try again? press y to try again");
choice=readCre.readLine();
if(!(choice.startsWith("y")))
{
flag=false;
}
}//end of 1st
else
}//end of
while
}//end of main
}//end of class
In the above example first we putted some keys and values in TreeMap as String, after putting key value pair we are taking input from the user to check users credential i.e., username and password using BufferedReader class and checking those credential see above example.
ouput :
Hope it will help you
:)
ouput :
Noraml TreeMap : {Mateen1=12341, Mateen2=12342, Mateen3=12343}
Enter Username
xyz
Enter Password
12341
Invalid User
Do you want to try again? press y to try again
y
Enter Username
Mateen1
Enter Password
ffvvsdv
Invalid Password
Do you want to try again? press y to try again
y
Enter Username
Mateen1
Enter Password
12341
Welcome Mateen1

No comments