[英]how to find number which are not in a arraylist?
所以我有一个Arraylist。 它目前持有整数。 我想从某个范围内获取不在 arraylist 中的整数列表。 例如,如果数字的范围是从 1 到 5,如果 arraylist 包含 1,3,4,那么输出应该是 2 和 5。存储在 ArrayList 中的数字也应该是唯一的,因此我正在考虑使用 Hashset。 到目前为止,这是我的代码:
HashSet<Integer> abc = new HashSet<>();
while(myrs.next()){
try {
//RoomIdsThatAreCurrentlyReserved.add(Integer.parseInt(myrs.getObject(1).toString()));
abc.add(Integer.parseInt(myrs.getObject(1).toString()));
} catch (SQLException e) {
e.printStackTrace();
我的代码基本上是从结果集中读取。
对于Eclipse Collections ,以下内容将使用MutableSet工作。 在这里使用MutableSet
,因为您似乎愿意使用Set
。
MutableSet<Integer> set = Sets.mutable.with(1, 2, 3, 4, 5);
MutableSet<Integer> anotherSet = Sets.mutable.with(2, 3, 4);
MutableSet<Integer> result = set.difference(anotherSet);
System.out.println(result); //[1, 5]
注意:我是 Eclipse Collections 的提交者。
这是一个简单的例子:
Arraylist a={1,2,3,4,5};
Arraylist b={2,3,4};
如果你不会像1
和5
这样的输出。 然后
简单地使用了这个:
List<Integer> c = new ArrayList<>(a);
c.removeAll(b);
你为什么不这样做,
Iterator iterator = hashSet.iterator();
while (iterator.hasNext()){
int currentIteratorValue = (int) iterator.next();
if(currentIteratorValue != 1 && currentIteratorValue != 3 && currentIteratorValue != 4){
System.out.println(currentIteratorValue); //Prints 5 and 2
}
}
使用https://github.com/google/guava (java 1.6)
List<Integer> fullList = Lists.newArrayList(1, 2, 3, 4 , 5);
List<Integer> partOfList = Lists.newArrayList(1, 3, 4 );
FluentIterable<Integer> missing = FluentIterable.from(fullList).filter(Predicates.not(Predicates.in(partOfList)));
这是一个 1-liner。
鉴于:
List<Integer> list; // populated elsewhere
// copy to a set if the list is large so it will perform better
Set<Integer> set = new HashSet<>(list);
然后:
List<Integer> missing = IntStream.range(a, b)
.filter(i -> !set.contains(i))
.collect(Collectors.toList());
如果列表很小,您可以跳过该集合并使用
.filter(i -> !list.contains(i))
但那是O(n)
而集合包含的是O(1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.