Syntax error Iterate through the values of TreeMap in Java

Iterate through the values of TreeMap in Java



Use Iterator and the values() method to iterate through the values of TreeMap.

Let us first create a TreeMap and add some elements −

TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"PHP");
m.put(2,"jQuery");
m.put(3,"JavaScript");
m.put(4,"Ruby");
m.put(5,"Java");
m.put(6,"AngularJS");
m.put(7,"ExpressJS");

Iterate through the values −

Collection res = m.values();
Iterator i = res.iterator();
while (i.hasNext()) {
   System.out.println(i.next());
}

The following is the complete example to iterate through the values −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"PHP");
      m.put(2,"jQuery");
      m.put(3,"JavaScript");
      m.put(4,"Ruby");
      m.put(5,"Java");
      m.put(6,"AngularJS");
      m.put(7,"ExpressJS");
      System.out.println("TreeMap Elements...");
      Collection res = m.values();
      Iterator i = res.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

Output

TreeMap Elements...
PHP
jQuery
JavaScript
Ruby
Java
AngularJS
ExpressJS
Updated on: 2019-07-30T22:30:24+05:30

732 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements