public static void main(String[] args) { List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)); Set<Integer> sets = new HashSet<>(16); sets.addAll(list); //foreach遍历 System.out.println("\n遍历1: foreach:"); for (Integer i : sets) { System.out.print(i + " "); } //iterator遍历 System.out.println("\n遍历2: iterator:"); Iterator<Integer> iterator = sets.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } //stream流遍历 System.out.println("\n遍历3: stream流"); sets.forEach(s -> System.out.print(s + " ")); //for循环遍历 System.out.println("\n遍历4:for循环"); Iterator<Integer> iterator2 = sets.iterator(); for (int i = 0; i < sets.size(); i++) { System.out.print(iterator2.next() + " "); } // forEachRemaining:底层实现while (hasNext()) action.accept(next()); System.out.println("\n遍历5:forEachRemaining"); sets.iterator().forEachRemaining(s -> System.out.print(s + " ")); }