Easy Tutorial
❮ Java String Comparetoignorecase Java String Split ❯

Java Example - Collection Output

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 Keys: " + tMap.keySet());
      System.out.println("TreeMap Values: " + tMap.values());
      System.out.println("Value for key 5: " + 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("Removing first data: " + tMap.remove(tMap.firstKey()));
      System.out.println("Now TreeMap Keys: " + tMap.keySet());
      System.out.println("Now TreeMap contains: " + tMap.values() + "\n");
      System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
      System.out.println("Now TreeMap Keys: " + tMap.keySet());
      System.out.println("Now TreeMap contains: " + tMap.values());
   }
}

The above code outputs the following result:

TreeMap Example!

TreeMap Keys: [1, 2, 3, 4, 5, 6, 7]
TreeMap Values: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
Value for key 5: Thursday

First Key: 1 Value: Sunday

Last Key: 7 Value: Saturday

Removing first data: Sunday
Now TreeMap Keys: [2, 3, 4, 5, 6, 7]
Now TreeMap contains: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]

Removing last data: Saturday
Now TreeMap Keys: [2, 3, 4, 5, 6]
Now TreeMap contains: [Monday, Tuesday, Wednesday, Thursday, Friday]

Java Example

❮ Java String Comparetoignorecase Java String Split ❯