iterator循环remove例子:
如下
public static void main(String[] args) {
List<String> strList = new ArrayList<String>();
strList.add("一");
strList.add("二");
strList.add("三");
strList.add("四");
strList.add("五");
strList.add("六");
strList.add("七");
List<String> strlocalList = new ArrayList<String>();
strlocalList.add("一");
strlocalList.add("四");
strlocalList.add("五");
Map<Object, Object> map = new HashMap<Object, Object>();
for(String str : strlocalList){
map.put(str, str);
}
Iterator<String> iterator = strList.iterator();
while(iterator.hasNext()){
String str = iterator.next();
if(null != map.get(str)){
iterator.remove();
}
}
System.out.println("map :" + map.toString());
System.out.println("strList :" + strList.toString());
System.out.println("strlocalList :" + strlocalList.toString());
}
结果:
map :{五=五, 一=一, 四=四}
strList :[二, 三, 六, 七]
strlocalList :[一, 四, 五]
for循环remove例子:
如下
public static void main(String[] args) {
List<String> strList = new ArrayList<String>();
strList.add("一");
strList.add("二");
strList.add("三");
strList.add("四");
strList.add("五");
strList.add("六");
strList.add("七");
List<String> strlocalList = new ArrayList<String>();
strlocalList.add("一");
strlocalList.add("四");
strlocalList.add("五");
Map<Object, Object> map = new HashMap<Object, Object>();
for(String str : strlocalList){
map.put(str, str);
}
for(int i = strList.size() - 1 ;i >= 0 ; i --){
String string = strList.get(i);
if(null != map.get(string)){
strList.remove(string);
}
}
System.out.println("map :" + map.toString());
System.out.println("strList :" + strList.toString());
System.out.println("strlocalList :" + strlocalList.toString());
}
结果:
map :{五=五, 一=一, 四=四}
strList :[二, 三, 六, 七]
strlocalList :[一, 四, 五]