Java入門–mapを操作するサンプルコード

Javaコード:
package com.utilTest;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapSampleDemo {
public static void main(String[] args) {
Map<String,String> map=new HashMap<String,String>(){{
put(“key1", “value11");
put(“key2", “value12");
put(“key3", “value13");
}};
//Iterator
Set<String> keySet=map.keySet();
for(Iterator<String> it=keySet.iterator();it.hasNext();){
String s=it.next();
System.out.println(map.get(s));
}

//key+each
for (String key : map.keySet()) {
System.out.println(“key= “+ key + " and value= " + map.get(key));
}
//values+iterator
Collection<String> c = map.values();
for(Iterator<String> it=c.iterator();it.hasNext();){
System.out.println(it.next());
}

//values+foreach
for (String v : map.values()) {
System.out.println(“value= " + v);
}
//map.entry
//set+map.entry+iterator
Set<Map.Entry<String, String>> set=map.entrySet();
for(Iterator<Map.Entry<String, String>> it=set.iterator();it.hasNext();){
Map.Entry<String, String> mapEnter=it.next();
System.out.println(“key="+mapEnter.getKey()+",value="+mapEnter.getValue());
}
//map.entry+foreach
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(“key= " + entry.getKey() + " and value= " + entry.getValue());
}
}
}

Java

Posted by arkgame