CodesJava

Easy learning with example program codes

Get all keys from treemap in java

We can use keySet() method to get all keys from treemap in java.

keySet(): Returns a Set that contains the keys in this map. This method provides a set-view of the keys in this map.

Syntax:

public Set keySet()

Example

package com.codesjava;
 
import java.util.Set;
import java.util.TreeMap;
 
public class Test {
  public static void main(String args[]){
	//Create TreeMap object.
	TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
 
	//Add objects to the TreeMap.
	treeMap.put(4, "Roxy");
	treeMap.put(2, "Sunil");
	treeMap.put(5, "Sandy");
	treeMap.put(1, "Munish");
	treeMap.put(3, "Pardeep");
 
	//Print the TreeMap object.
	System.out.println("TreeMap elements:");
	System.out.println(treeMap);
 
	Set<Integer> keys = treeMap.keySet();
        for(Integer key: keys){
            System.out.println(key);
        }
  }
}

Output

TreeMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
1
2
3
4
5
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status