import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
public class parcours_treemap {
public static void main(String args[]) {
/* TreeMap declaration */
TreeMaptm = new TreeMap ();
/*Add elements to TreeMap*/
tm.put(12, "val1");
tm.put(5, "val2");
tm.put(8, "val3");
tm.put(2, "val4");
/* Display content using Iterator */
Set set = tm.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mapentry = (Map.Entry)iterator.next();
System.out.print("key: "+ mapentry.getKey() + " +
"- value: "+mapentry.getValue()+"\n");
}
}
}
key: 2 - value: val4We can see that the couples< key, value> are sorted in ascending order by keys.
key: 5 - value: val2
key: 8 - value: val3
key: 12 - value: val1
import java.util.TreeMap;Executing this code outputs this result:
public class parcours {
public static void main(String args[]) {
/* TreeMap declaration */
TreeMaptm = new TreeMap ();
/*Add elements to TreeMap*/
tm.put(12, "val1");
tm.put(5, "val2");
tm.put(8, "val3");
tm.put(2, "val4");
TreeMaptm2 = new TreeMap ();
tm2.putAll(tm);
/*display a few pairs just to check */
System.out.print("key: 12" + " - value: "+tm2.get(12)+"\n");
System.out.print("key: 8" + " - value: "+tm2.get(8)+"\n");
/*first and last key*/
System.out.print("first key: "+tm2.firstKey()+" last key: "+tm2.lastKey());
}
}
key: 12 - value: val1References:
key: 8 - value: val3
first key: 2 last key: 12
Please disable your ad blocker and refresh the window to use this website.