- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a TreeMap in Java and add key-value pairs
A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.
Let us first see how to create a TreeMap −
TreeMap<Integer,String> m = new TreeMap<Integer,String>();
Add some elements in the form of key-value pairs −
m.put(1,"India"); m.put(2,"US"); m.put(3,"Australia"); m.put(4,"Netherlands"); m.put(5,"Canada");
The following is an example to create a TreeMap and add key-value pairs −
Example
import java.util.*; public class Demo { public static void main(String args[]) { TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"India"); m.put(2,"US"); m.put(3,"Australia"); m.put(4,"Netherlands"); m.put(5,"Canada"); for(Map.Entry e:m.entrySet()) { System.out.println(e.getKey()+" "+e.getValue()); } } }
Output
1 India 2 US 3 Australia 4 Netherlands 5 Canada
- Related Articles
- Java Program to create a HashMap and add key-value pairs
- Remove a key from TreeMap in Java
- How to add key/value pairs in SortedList in C#?
- Get lowest key stored in Java TreeMap
- JavaScript: How to Create an Object from Key-Value Pairs
- Remove a value from TreeMap in Java
- Create NavigableMap from TreeMap in Java
- Java Program to get highest key stored in TreeMap
- Java Program to check if a particular key exists in TreeMap
- Java Program to remove a key from a TreeMap only if it is associated with a given value
- Add key and value into StringDictionary in C#
- Python Program to print key value pairs in a dictionary
- Add key and value into OrderedDictionary collection in C#
- Add a key value pair to dictionary in Python
- Java Program to check if a particular value exists in TreeMap

Advertisements