java中从Map集合里面取键和值的四种方式
package com.first.test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Test23 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//将值的类型定义成Object的好处,就是啥类型的数据都可以存储
Map map = new HashMap();
map.put(“1”, 123);
map.put(“2”, “abc”);
map.put(“3”, 6.98);
System.out.println(“第1种方式:”);
Set set = map.keySet();
for(String array: set) {
System.out.print(array + “:”); //获取键
System.out.print(map.get(array) + “, “); //获取值
}
System.out.println(“”);
//上面的代码可以直接合二为一(可以使用等值替换的方式)
for(String s: map.keySet()) {
System.out.print(s + “:”); //获取键
System.out.print(map.get(s) + “, “); //获取值
}
System.out.println(“”);
System.out.println(“—————————“);
System.out.println(“第2种方式:”);
//只是获取值的时候,集合的类型需要定义成Collection,其中T是你自己Map集合中值的数据类型
Collection setValue = map.values();
for(Object array01: setValue) {
System.out.print(array01 + “, “); //获取值
}
System.out.println(“”);
System.out.println(“—————————“);
System.out.println(“第3种方式:”);
//使用迭代器的方式
Iterator i1 = map.keySet().iterator();
while(i1.hasNext()) {
String key = i1.next();
System.out.print(key + “:”); //获取键
System.out.print(map.get(key)+ “, “); //获取值
//不能出现两次i1.next()方法,会报错
//System.out.print(i1.next() + “:”);
//System.out.print(map.get(i1.next())+ “,”); //使用这句代码会报错
}
System.out.println(“”);
Set set1 = map.keySet();
Iterator i2 = set1.iterator();
while(i2.hasNext()) {
String key = i2.next();
Object value= map.get(key); /
System.out.print(key+”:”); //获取键
System.out.print(value + “, “); //获取值
}
System.out.println(“”);
System.out.println(“—————————“);
System.out.println(“第4种方式:”);
for(Entry entry: map.entrySet()) {
System.out.print(entry.getKey() + “:”); //获取键
System.out.print(entry.getValue() + “, “); //获取值
}
System.out.println(“”);
Set<Entry> setEntry = map.entrySet();
for (Entry entry : setEntry) {
String key = entry.getKey();
Object value = entry.getValue(); /
System.out.print(key+”: “); //获取键,获取值
System.out.print(value + “, “); //获取键,获取值
}
}
}
特别声明:研究发表不易,禁止转载和抄袭。
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/0413abbcfa.html
