关于常识性的Map的key和value的操作
package zy.stu.com;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* 对Map的移除操作,以及键和value的操作
* @author zy962
*
*/
public class MapIt {
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
map1.put("11", "A11");
map1.put("12", "A12");
map1.put("13", "A13");
map1.put("14", "A14");
map1.put("25", "A15");
map1.put("26", "A16");
map2.put("11", "A11");
map2.put("12", "A12");
map2.put("23", "A13");
map2.put("24", "B21");
map2.put("25", "B21");
// 移除map1中key为2开头的,map2中value为2开头的
// entrySet获得里面的key和value值
Iterator<Map.Entry<String, String>> it1 = map1.entrySet().iterator();
while (it1.hasNext()) {
Entry<String, String> entry = it1.next();
if (entry.getKey().startsWith("2")) {
it1.remove();
}
}
Iterator<Map.Entry<String, String>> it2 = map1.entrySet().iterator();
while (it2.hasNext()) {
Entry<String, String> entry = it2.next();
if (entry.getValue().startsWith("2")) {
it2.remove();
}
}
// 将map1中key为11,value为A11的改为value为C11
while (it1.hasNext()) {
Entry<String, String> en = it1.next();
if (en.getKey() == "11" && en.getValue() == "A11") {
en.setValue("C11");
}
}
// 比较map1和map2的相同的key,value值,输出。
while (it2.hasNext()) {
Entry<String, String> entry = it2.next();
if (map1.containsKey(entry.getKey()) && map1.containsValue(entry.getValue())) {
System.out.println(entry.getValue());
}
}
}
}