How to Iterate over a Set/HashSet without an Iterator?

后端 未结 8 2033
闹比i
闹比i 2020-12-02 03:29

How can I iterate over a Set/HashSet without the following?

Iterator iter = set.iterator();
while (iter.hasNext()) {
    System.out         


        
8条回答
  •  忘掉有多难
    2020-12-02 04:24

    There are at least six additional ways to iterate over a set. The following are known to me:

    Method 1

    // Obsolete Collection
    Enumeration e = new Vector(movies).elements();
    while (e.hasMoreElements()) {
      System.out.println(e.nextElement());
    }
    

    Method 2

    for (String movie : movies) {
      System.out.println(movie);
    }
    

    Method 3

    String[] movieArray = movies.toArray(new String[movies.size()]);
    for (int i = 0; i < movieArray.length; i++) {
      System.out.println(movieArray[i]);
    }
    

    Method 4

    // Supported in Java 8 and above
    movies.stream().forEach((movie) -> {
      System.out.println(movie);
    });
    

    Method 5

    // Supported in Java 8 and above
    movies.stream().forEach(movie -> System.out.println(movie));
    

    Method 6

    // Supported in Java 8 and above
    movies.stream().forEach(System.out::println);
    

    This is the HashSet which I used for my examples:

    Set movies = new HashSet<>();
    movies.add("Avatar");
    movies.add("The Lord of the Rings");
    movies.add("Titanic");
    

提交回复
热议问题