我必须找到一种最佳方法来找出第二个arraylist中未呈现的元素。假设
Arraylist a,b,
Arraylist a={1,2,3,4,5};
Arraylist b={2,3,4};
基本上我想要的是找出 a 的元素,该元素在 arraylist b 中不存在。
那么最好的解决方案是什么?
List<Integer> c = new ArrayList<>(a);
c.removeAll(b);
还考虑使用集合而不是列表。
这是使用Java 8-
的另一种方法a.stream().filter(b::contains).collect(Collectors.toList());
您可以使用Apache Commons Collections,该方法明确为此目的:
public static void main(String[] args) {
List<Integer> a = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
List<Integer> b = Arrays.asList(new Integer[] { 2, 3, 4 });
Collection<Integer> aMinusB = CollectionUtils.subtract(a, b);
System.out.println(aMinusB);
}
印刷结果是: [1,5] 。
apache commons lib经过良好的测试,通常用于扩展标准Java功能。此特定方法接受Iterable
作为参数,因此您可以使用所需的任何Collection
。您还可以混合不同的收集类型:
public static void main(String[] args) {
List<Integer> a = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
Set<Integer> b = new HashSet<Integer>(Arrays.asList(new Integer[] { 2, 3, 4 }));
Collection<Integer> aMinusB = CollectionUtils.subtract(a, b);
System.out.println(aMinusB);
}
印刷结果相同, [1,5] 。
在此处查看Javadoc。
为了完整,Google的Guava库没有此功能:
中的每个元素上删除它
Collection *subtract*(Collection, Collection)
没有等效的 - 创建包含a的阵列列表,然后在b。
但是,它实现了一种称为Sets.difference()
方法的方法,如果您喜欢guava并使用集合:
public static void main(String[] args) {
Set<Integer> a = new HashSet<Integer>(Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }));
Set<Integer> b = new HashSet<Integer>(Arrays.asList(new Integer[] { 2, 3, 4 }));
Set<Integer> aMinusB = Sets.difference(a, b);
System.out.println(aMinusB);
}
结果是a
中不存在b
中不存在的所有元素(即再次[1,5] )。当然,由于该订单在集合上运行。
您可以尝试removeAll
:
List<Integer> notPresent = new ArrayList<Integer>(a);
notPresent.removeAll(b);
使用org.apache.commons.collections4.ListUtils
给定
List<Integer> a = Arrays.asList(new Integer[]{ 1,2,3,4,5});
List<Integer> b = Arrays.asList(new Integer[]{0,1,2,3});
动作
List<Integer> c = ListUtils.removeAll(b, a)
结果列表c
4, 5
请尝试以下尝试
for (Object o : a) {
if (!b.contains(o)) {
// this is not present
}
}
循环通过一个列表,然后检查其他列表中的每个元素是否使用包含。
类似的东西。如果您认为a
中可能会有重复项,则可以尝试另一种类型的Collection
,例如Set
的notPresent
。
List<Integer> notPresent = new ArrayList<Integer>();
for (Integer n : a){
if (!b.contains(n)){
notPresent.add(n);
}
}
尝试以下:
public static void main(String[] args) {
List<Integer> a = new ArrayList<Integer>();
List<Integer> b = new ArrayList<Integer>();
List<Integer> exclusion = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
b.add(1);
b.add(2);
b.add(3);
b.add(5);
for (Integer x : a) {
if (!b.contains(x)) {
exclusion.add(x);
}
}
for (Integer x : exclusion) {
System.out.println(x);
}
}
尝试这个...
使用列表的contains()
方法。
ArrayList<Integer> aList = new ArrayList<Integer>();
for (Integer i : a){
if (!(b.contains(i))){
aList.add(i);
}
else{
continue;
}
}