Java中遍历集合的常用方法

一、List

1、普通for循环

for (int i = 0; i < list.size(); i++)){
	String temp = (String)list.get(i);
	System.out.println(temp);
}

  

2、增强for循环(使用泛型)

for (String temp: list) {
	System.out.println(temp);
}

  

3、使用Iterator迭代器

for (Iterator it = list.iterator(); it.hasNext();) {
	String temp = (String)it.next();
	System.out.println(temp);
}

  

4、使用Iterator迭代器

Iterator it = list.iterator();
while(it.hasNext()) {
	Object obj = it.next();
	it.remove(); // 如果遍历时要删除集合中的元素
	System.out.println(obj);
}

  

 

二、Set

 

1、增强for循环

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

  

2、使用Iterator迭代器

for (Iterator<String> it = set.iterator(); it.hasNext();) {
	String temp = (String)it.next();
	System.out.println(temp);		
}

  

三、Map

 

1、根据key获取value

Set<Integer> s2 = map1.keySet();
for (Iterator<Integer> it = s2.iterator(); it.hasNext();) {
	Integer temp = it.next();
	System.out.println(temp + " " + map1.get(temp));
}

  

2、使用entrySet

Set<Entry<Integer, String>> s1 = map1.entrySet();
for (Iterator<Entry<Integer, String>> it = s1.iterator(); it.hasNext();) {
	Entry<Integer, String> temp = it.next();
	System.out.println(temp.getKey() + " " + temp.getValue());
			
}

  

posted @ 2020-05-11 10:54  牛肉叉烧饭w  阅读(243)  评论(0编辑  收藏  举报
levels of contents