Share this page 

Dump the content of a Collection (JDK 1.5)Tag(s): Language


List
public class DumpCollection {
  public static void main(String[] args) {
    java.util.ArrayList<String> theSimpsons = new
          java.util.ArrayList<String>();
    theSimpsons.add("Bart");
    theSimpsons.add("Lisa");
    theSimpsons.add("Marge");
    theSimpsons.add("Barney");
    theSimpsons.add("Homer");
    theSimpsons.add("Maggie");

    for (String character: theSimpsons) {
      System.out.println(character);
    }
  }
}

Or convert the list as an Array :

     System.out.println(java.util.Arrays.toString(theSimpsons.toArray()));

     /*
     output :  [Bart, Lisa, Marge, Barney, Homer, Maggie]
     */
Map
import java.util.*;
import java.io.*;

public class DumpCollection {
  public static void main(String[] args) {
    Map<String,File> theSimpsons = new HashMap<String,File>();
    theSimpsons.put("Bart", new File("Bart.jpg"));
    theSimpsons.put("Lisa", new File("Lisa.jpg"));
    theSimpsons.put("Marge", new File("Marge.jpg"));
    theSimpsons.put("Barney", new File("Barney.jpg"));
    theSimpsons.put("Homer", new File("Homer.jpg"));
    theSimpsons.put("Maggie", new File("Maggie.jpg"));
    dump(theSimpsons);
  }
  
  public static void dump(Map<?,?> map) {
    for (Map.Entry<?,?> entry : map.entrySet()) {
      System.out.println(entry.getKey() + ": " + entry.getValue());
    }
  }
}

/*
output :

Bart: Bart.jpg
Lisa: Lisa.jpg
Maggie: Maggie.jpg
Homer: Homer.jpg
Barney: Barney.jpg
Marge: Marge.jpg
*/