Map遍历
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
map.put("4", "4");
//通过Map.keySet遍历key和value
for (String key : map.keySet())
System.out.println(key + ":" + map.get(key));
//通过Map.entrySet使用iterator遍历key和value
Iterator<Map.Entry<String, String>> ito = map.entrySet().iterator();
while (ito.hasNext()) {
Map.Entry<String, String> entry = ito.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
//通过Map.entrySet遍历key和value
for (Map.Entry<String, String> entry : map.entrySet())
System.out.println(entry.getKey() + ":" + entry.getValue());
//通过Map.values()遍历所有的value,但不能遍历key
for (String value : map.values())
System.out.println(value);
}
}
List遍历
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
//使用foreach遍历List
for (String string : list)
System.out.println(string);
//变为数组相关的内容进行遍历
String[] strArry = new String[list.size()];
list.toArray(strArry);
for (String str : strArry)
System.out.println(str);
//使用迭代器进行相关遍历
Iterator<String> ito = list.iterator();
while (ito.hasNext())
System.out.println(ito.next());
}
}
网友评论