在本节中,我们将看到迭代HashSet的示例。这里将使用迭代Set:
- For-Each循环
- Iterator 接口
- Stream(在Java8中引入)
文件:IterateSetExample.java –
package com.yiibai.tutorial; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @author yiibai * */ public class IterateSetExample { public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays .asList(new String[] { "Java" "Jsp" "Servlet" "Jdbc" "Collection" })); /* Method 1 - Iterating using for loop */ System.out.println("Method 1 - Iterating using for-each loop"); for (String string : set) { System.out.println(string); } /* Method 2 - Iterating using Iterator */ System.out.println(" Method 2 - Iterating using Iterator"); Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } /* Method 3 - Iterating using Stream */ System.out.println(" Method 3 - Iterating using Stream"); set.stream().forEach(a -> System.out.println(a)); } }
执行上面示例代码,得到以下结果 –
Method 1 - Iterating using for-each loop Java Jsp Jdbc Servlet Collection Method 2 - Iterating using Iterator Java Jsp Jdbc Servlet Collection Method 3 - Iterating using Stream Java Jsp Jdbc Servlet Collection
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264144.html