Java Examples - Collection Output
The following example demonstrates how to use the tMap.keySet(), tMap.values() and tMap.firstKey() methods of the Java Util class to output collection elements:
Main.java file
import java.util.*;
public class Main{
public static void main(String[] args) {
System.out.println("TreeMap Example!\n");
TreeMap tMap = new TreeMap();
tMap.put(1, "Sunday");
tMap.put(2, "Monday");
tMap.put(3, "Tuesday");
tMap.put(4, "Wednesday");
tMap.put(5, "Thursday");
tMap.put(6, "Friday");
tMap.put(7, "Saturday");
System.out.println("TreeMap keys:"
+ tMap.keySet());
System.out.println("TreeMap values:"
+ tMap.values());
System.out.println("The value for key 5 is:" + tMap.get(5)+ "\n");
System.out.println("First key:" + tMap.firstKey()
+ " Value: "
+ tMap.get(tMap.firstKey()) + "\n");
System.out.println("Last key:" + tMap.lastKey()
+ " Value: "+ tMap.get(tMap.lastKey()) + "\n");
System.out.println("Remove the first data:"
+ tMap.remove(tMap.firstKey()));
System.out.println("Now TreeMap keys are:"
+ tMap.keySet());
System.out.println("Now TreeMap contains:"
+ tMap.values() + "\n");
System.out.println("Remove the last data:"
+ tMap.remove(tMap.lastKey()));
System.out.println("Now TreeMap keys are:"
+ tMap.keySet());
System.out.println("Now TreeMap contains:"
+ tMap.values());
}
}
The output of running the above code is:
TreeMap 实例! TreeMap 键:[1, 2, 3, 4, 5, 6, 7] TreeMap 值:[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] 键为 5 的值为: Thursday 第一个键: 1 Value: Sunday 最后一个键: 7 Value: Saturday 移除第一个数据: Sunday 现在 TreeMap 键为: [2, 3, 4, 5, 6, 7] 现在 TreeMap 包含: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] 移除最后一个数据: Saturday 现在 TreeMap 键为: [2, 3, 4, 5, 6] 现在 TreeMap 包含: [Monday, Tuesday, Wednesday, Thursday, Friday]Other extensions
Java Examples