Traversal methods of Java collections Set, List, and Map

The examples in this article describe the traversal methods of Java collections Set, List, and Map, and share them with you for your reference. The specific methods are as follows: package com.shellway.javase; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.junit.Test; public class TestCollection { public static void print(Collection c){ Iterator it = c.iterator(); while (it.hasNext()) { Object object = (Object) it.next(); System.out.println(object); } } @Test public void demo1(){ Set set = new HashSet(); set.add(“AAA”); set.add(“BBB”); set.add(“CCC”); print(set); //The first traversal method of Set: using Iterator Iterator it1 = set.iterator(); for (String ss : set) { System.out.println(ss); } //The first traversal method of Set: using foreach for (String sss : set) { System.out.println(sss); } List list = new ArrayList(); list.add(“DDDDD”); list.add(“EEEEE”); list.add(“FFFFF”); print(list); //The first traversal method of List: because the list has order, use the size() and get() methods to obtain for (int i = 0; i <list.size(); i++) { System.out.println(list.get(i)); } //The second way to traverse List: using Iterator Iterator it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } //The third way to traverse List: using foreach for (String s2 : list) { System.out.println(s2); } Map map = new TreeMap();…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索