假设我有这些列表:
List<Integer> numbersA=new ArrayList<Integer>();
List<Integer> numbersB=new ArrayList<Integer>();
“数字A”是[1,3,4,7,5,2](没有重复的数字) 和“数字B”是:[13,32,533,3,4,2]
因此该方法将从“数字B”中删除“数字A”,并且“数字B”将是: [13,32,533]
答案 0 :(得分:2)
使用方法删除所有,此处为doc
public static void main(String[] args) {
List<Integer> numbersA = new ArrayList<>();
List<Integer> numbersB = new ArrayList<>();
numbersA.addAll(Arrays.asList(new Integer[] { 1, 3, 4, 7, 5, 2 }));
numbersB.addAll(Arrays.asList(new Integer[] { 13, 32, 533, 3, 4, 2 }));
System.out.println("A: " + numbersA);
System.out.println("B: " + numbersB);
numbersB.removeAll(numbersA);
System.out.println("B cleared: " + numbersB);
}
这将打印
答:[1,3,4,7,5,2]
B:[13,32,533,3,4,2]
B清除:[13,32,533]
答案 1 :(得分:0)
您可以使用List的boolean removeAll(Collection<?> c);
方法。它将删除共同元素。
numbersB.removeAll(numbersA);
答案 2 :(得分:0)
Java 8 version
版本1改变原始数组
Integer [] array1 = new Integer[]{1,3,4,7,5,2};
Integer [] array2 = new Integer[]{13,32,533,3,4,2};
List<Integer> numbersA=Arrays.asList(array1);
final List<Integer> numbersB=Arrays.asList(array2);
numbersA.stream().forEach(t->numbersB.remove(t));
版本1使用过滤器并返回新列表
Integer [] array1 = new Integer[]{1,3,4,7,5,2};
Integer [] array2 = new Integer[]{13,32,533,3,4,2};
List<Integer> numbersA=Arrays.asList(array1);
final List<Integer> numbersB=Arrays.asList(array2);
List<Integer> numbersA.stream().filter(t->numbersB.contains(t)).collect(Collectors.toList());