How can Java output the elements in a collection?

To print elements in a collection in Java, you can loop through the collection elements and then use the System.out.println() method to print each element. Here are the specific steps:

  1. Import the java.util package to utilize collection classes.
import java.util.*;
  1. Create a collection object, for example an ArrayList:
List<String> list = new ArrayList<>();
  1. Add elements to the collection.
list.add("元素1");
list.add("元素2");
list.add("元素3");
  1. Iterate through the collection using a loop and print out each element.
for(String element : list) {
    System.out.println(element);
}

The complete example code is as follows:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("元素1");
        list.add("元素2");
        list.add("元素3");
        
        for(String element : list) {
            System.out.println(element);
        }
    }
}

Running the code above will output the elements in the set.

元素1
元素2
元素3
bannerAds