Java之List和Map的几种遍历方法:
程序员文章站
2024-02-17 12:16:28
...
package com.example.zhangqianqian.java_project;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class List_Map {
public static void main(String[] args){
//list
List<String> list = new ArrayList<>();
list.add("code1");
list.add("code2");
list.add("code3");
//遍历方法1:for方法
for(String chara : list){
//System.out.println(chara);
}
for(int i = 0;i < list.size();i++){
//System.out.println(list.get(i));
}
// 遍历方法2:转换成数组
String[] strArray = new String[list.size()];
list.toArray(strArray);
for(int i = 0;i < strArray.length;i++){
//System.out.println(strArray[i]);
}
for(String str : strArray){
//System.out.println(str);
}
//遍历方法3:iterator方法
Iterator<String> ite = list.iterator();
while(ite.hasNext()){
System.out.println(ite.next());
}
//Map
Map<String,String> hashMap = new HashMap<String,String>();
hashMap.put("code1","Content1");
hashMap.put("code2","Content2");
hashMap.put("code3","Content3");
//遍历方法1:二次取值
for(String key:hashMap.keySet()){
System.out.println("HashMap 的 Key值:"+key+" Value值:"+hashMap.get(key));
}
//遍历方法2:Iterator方法
Iterator<Map.Entry<String,String>> it = hashMap.entrySet().iterator();
while (it.hasNext()){
Map.Entry<String,String> entry = it.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println("Key = "+key+" value = "+value);
}
//遍历方法3:for方法+entry(量大使用)
for(Map.Entry<String,String> entry : hashMap.entrySet()){
System.out.println("Key:" + entry.getKey());
System.out.println("Vaule:" + entry.getValue());
}
//遍历方法4:获取values
for(String v : hashMap.values()){
System.out.println(v);
}
}
}
上一篇: 微信支付之APP支付