Java 示例 - 打印集合

  • 问题描述

    如何打印收藏?
  • 解决方案

    以下示例如何使用 Java Util 类的 tMap.keySet()、tMap.values() 和 tMap.firstKey() 方法打印集合。
    
    import java.util.*;
    public class TreeExample{
       public static void main(String[] args) {
          System.out.println("Tree Map Example!\n");
          TreeMap <Integer, String>tMap = new TreeMap<Integer, String>();
          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("Keys of tree map: " + tMap.keySet());
          System.out.println("Values of tree map: " + tMap.values());
          System.out.println("Key: 5 value: " + 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 the tree map Keys: " + tMap.keySet());
          System.out.println("Now the tree map contain: " + tMap.values() + "\n");
          System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
          System.out.println("Now the tree map Keys: " + tMap.keySet());
          System.out.println("Now the tree map contain: " + tMap.values());
       }
    }
    
  • 结果

    上面的代码示例将产生以下结果。
    
    C:\collection>javac TreeExample.java
    C:\collection>java TreeExample
    Tree Map Example!
    Keys of tree map: [1, 2, 3, 4, 5, 6, 7]
    Values of tree map: [Sunday, Monday, Tuesday, Wednesday, 
    Thursday, Friday, Saturday]
    Key: 5 value: Thursday
    First key: 1 Value: Sunday
    Last key: 7 Value: Saturday
    Removing first data: Sunday
    Now the tree map Keys: [2, 3, 4, 5, 6, 7]
    Now the tree map contain: [Monday, Tuesday, Wednesday,
    Thursday, Friday, Saturday]
    Removing last data: Saturday
    Now the tree map Keys: [2, 3, 4, 5, 6]
    Now the tree map contain: [Monday, Tuesday, Wednesday,
    Thursday, Friday]
    C:\collection>