在JAVA中集合可以大致分为以下三类分别从connection接口延伸的List,Set,键值对形式Map.这三种适合的遍历方式
List的遍历:List<String> list = new ArrayList<String>();
①绝大多数人会用的,普通的for循环例:for(int i=0;i<list.size();i++){System.out.println(list(
i));}
②增强for循环
例:for(String value : list){System.out.println(value);}
③迭代器iterator
例:Iterator<String> it = list.iterator();
while (it.hasNext()) {
String value = it.next();
System.out.println(value);}
Set集合遍历Set<String> set = new HashSet<String>();
①迭代器iterator
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String value = it.next();
System.out.println(value);}
②使用增强for循环。
for(String s: set){
System.out.println(s);
}
键值对map
①private static void strongForMethod2(Map<String, String> maps) {
Set<Entry<String, String>> set = maps.entrySet();
for (Entry<String, String> entry : set) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " : " + value);
②private static void strongForMethod1(Map<String, String> maps) {
Set<String> set = maps.keySet();
for (String s : set) {
String key = s;
String value = maps.get(s);
System.out.println(key + " : " + value);
}
③:// 使用keySet()方法,获取maps集合中的所有键,遍历键取得所对应的值。
private static void traditionalMethod1(Map<String, String> maps) {
Set<String> sets = maps.keySet();
// 取得迭代器遍历出对应的值。
Iterator<String> it = sets.iterator();
while (it.hasNext()) {
String key = it.next();
String value = maps.get(key);
System.out.println(key + " : " + value);
}
④:/ 使用entrySet()方法,获取maps集合中的每一个键值对,
private static void traditionalMethod2(Map<String, String> maps) {
Set<Map.Entry<String, String>> sets = maps.entrySet();
// 取得迭代器遍历出对应的值。
Iterator<Entry<String, String>> it = sets.iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = (Entry<String, String>) it.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " : " + value);
}