This code example shows how to get the size or number of keys and values stored in TreeMap using the size().
To get the size, use the size() of the TreeMap class that returns the number of key/value pairs stored in a TreeMap of objects.
The results obtained are displayed before and after adding and removing elements.
JavaDoc: TreeMap size() method
To get the size, use the size() of the TreeMap class that returns the number of key/value pairs stored in a TreeMap of objects.
The results obtained are displayed before and after adding and removing elements.
import java.util.*;Output:
public class TreeMap_size {
public static void main(String[] args) {
// creating TreeMap
TreeMap< Integer, String> treemap = new TreeMap< Integer, String> ();
// insert into treemap
treemap.put(1, "ab");
treemap.put(2, "ba");
treemap.put(3, "bc");
//display elements
Set set=treemap.keySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()){
Integer key = ((Integer) iterator.next());
String val = ((String) treemap.get(key));
System.out.println(key+"-> "+val);
}
//initial treemap size
System.out.println("before: "+treemap.size()+" element(s)");
//add key/value
treemap.put(4, "cb");
System.out.println("after adding: "+treemap.size()+" element(s)");
String val = treemap.remove(3);
System.out.println("after removing "+val+": "+treemap.size()+" element(s)");
}
}
1-> abReferences:
2-> ba
3-> bc
before: 3 item(s)
after addition: 4 item(s)
after deletion of bc: 3 item(s)
JavaDoc: TreeMap size() method
Commentaires (0)
Laisser un commentaire
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Chargement des commentaires...