YouTip LogoYouTip

Collection Print

# Java Example - Collection Output [![Image 3: Java Example](#) Java Example](#) 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 Key: " + tMap.keySet()); System.out.println("TreeMap Value:" + tMap.values()); System.out.println("The value for key 5 is: " + tMap.get(5)+ "n"); System.out.println("The first key: " + tMap.firstKey() + " Value: " + tMap.get(tMap.firstKey()) + "n"); System.out.println("The 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 the above code is: TreeMap Example!TreeMap Key:[1, 2, 3, 4, 5, 6, 7]TreeMap Value:[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]The value for key 5 is: ThursdayThe first key: 1 Value: SundayThe last key: 7 Value: SaturdayRemove the first data: SundayNow TreeMap keys are: [2, 3, 4, 5, 6, 7]Now TreeMap contains: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]Remove the last data: SaturdayNow TreeMap keys are: [2, 3, 4, 5, 6]Now TreeMap contains: [Monday, Tuesday, Wednesday, Thursday, Friday] [![Image 4: Java Example](#) Java Example](#)
← Collection ReverseCollection Compare β†’