问题

如何在没有以下情况下迭代aSet / HashSet

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

#1 热门回答(401 赞)

你可以使用anenhanced for loop

Set<String> set = new HashSet<String>();

//populate set

for (String s : set) {
    System.out.println(s);
}

或者使用Java 8:

set.forEach(System.out::println);

#2 热门回答(64 赞)

至少有六种方法可以迭代一组。以下是我所知道的:
方法1

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

方法2

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

方法3

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

方法4

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

方法5

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

方法6

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

这是我用于我的例子的HashSet

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

#3 热门回答(19 赞)

将你的集转换为数组也可以帮助你迭代元素:

Object[] array = set.toArray();

for(int i=0; i<array.length; i++)
   Object o = array[i];

原文链接