业务场景
集合A 包含 1,2,3,4,5 等数据
集合B 包含 2,6 数据
要求 剔除 集合A中B的重复数据
1.集合元素删除
List moveList = new ArrayList<>();
moveList.add("5");
moveList.add("6");
List allList = new ArrayList<>();
allList.add("1");
allList.add("2");
allList.add("3");
allList.add("4");
allList.add("5");
allList.add("6");
allList.add("9");
for (String move :moveList){
for (String all: allList){
if(move.equals(all)){
allList.remove(all);
}
}
}
for (String n : allList){
System.out.print(n+" ");
}
是不是看起来没什么问题。。。。
运行一下
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
ConcurrentModificationException 可以自行百度。不再赘述。
2.集合删除改造版本 iterator
public static void main(String[] args) {
List moveList = new ArrayList<>();
moveList.add("5");
moveList.add("6");
List allList = new ArrayList<>();
allList.add("1");
allList.add("2");
allList.add("3");
allList.add("4");
allList.add("5");
allList.add("6");
allList.add("9");
Iterator iterator = allList.iterator();
for (String move : moveList) {
while (iterator.hasNext()){
String next = iterator.next();
if (next.equals(move)){
iterator.remove();
break;
}
}
}
for (String n : allList) {
System.out.print(n + " ");
}
}
运行一下,搞定
1 2 3 4 9
Process finished with exit code 0
3. 换一种写法 jdk1.8 流特性 Stream
static boolean isSame(List list, String element){
for (String l:list){
if(element.equals(l)){
return false;
}
}
return true;
}
public static void main(String[] args) {
List moveList = new ArrayList<>();
moveList.add("5");
moveList.add("6");
List allList = new ArrayList<>();
allList.add("1");
allList.add("2");
allList.add("3");
allList.add("4");
allList.add("5");
allList.add("6");
allList.add("9");
Stream stream = allList.stream();
List result = stream.filter(c -> isSame(moveList, c)).collect(Collectors.toList());
for (String n : result) {
System.out.print(n + " ");
}
}
运行一下,搞定
1 2 3 4 9
Process finished with exit code 0
同时,对于初始化集合优化
//Arrays.asList()
List moveList = Arrays.asList("5","11");