beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

TreeMap Iterator example – Java

By Chaitanya Singh | Filed Under: Java Collections

In this example we are iterating a TreeMap using Iterator and Map.Entry.

import java.util.TreeMap;
import java.util.Set;
import java.util.Map;
import java.util.Iterator;
public class TreeMapExample {
 
  public static void main(String[] args) {
 
    // Create a TreeMap
    TreeMap<String, String> treemap = new TreeMap<String, String>();
 
    // Add key-value pairs to the TreeMap
    treemap.put("Key1","Item1");
    treemap.put("Key2","Item2");
    treemap.put("Key3","Item3");
    treemap.put("Key4","Item4");
    treemap.put("Key5","Item5");
 
    // Get a set of the entries
    Set set = treemap.entrySet();
 
    // Get an iterator
    Iterator it = set.iterator();
 
    // Display elements
    while(it.hasNext()) {
      Map.Entry me = (Map.Entry)it.next();
      System.out.print("Key is: "+me.getKey() + " & ");
      System.out.println("Value is: "+me.getValue());
    } 
  }
}

Output:

Key is: Key1 & Value is: Item1
Key is: Key2 & Value is: Item2
Key is: Key3 & Value is: Item3
Key is: Key4 & Value is: Item4
Key is: Key5 & Value is: Item5

References:
TreeMap javadoc
Iterator javadoc
Map.Entry javadoc

Enjoyed this post? Try these related posts

  1. Java – Get first and last elements from LinkedList example
  2. Java – Add element at specific index in LinkedList example
  3. Difference between List and Set in Java
  4. How to Sort Vector using Collections.sort in java – Example
  5. Difference between HashMap and Hashtable
  6. Java – Remove first and last element from LinkedList example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2019 BeginnersBook . Privacy Policy . Sitemap