[英]Remove an item from a list and return the item
I have an ArrayList
and I want to check if an element exist in the list and if it exist I want to remove it and return it.我有一个
ArrayList
,我想检查列表中是否存在某个元素,如果存在,我想将其删除并返回。
I tried to use removeIf
but it returns a boolean
value.我尝试使用
removeIf
但它返回boolean
值。
How can I do that?我怎样才能做到这一点?
Thanks!谢谢!
LE乐
I have a list of objects Test:我有一个对象列表测试:
private static List<Test> tests = new ArrayList<>();
I have the method public Test deleteById(long id) {}
.我有方法
public Test deleteById(long id) {}
。
What I want is to check if tests
contains a test with id
and if that is true I want to remove the object and return it.我想要的是检查
tests
是否包含带有id
的测试,如果是,我想删除 object 并返回它。
If you want to find an element by a certain predicate, remove it and return it, you can have a method like this:如果你想通过某个谓词找到一个元素,删除它并返回它,你可以有这样的方法:
public static <E> E findRemoveAndReturn(List<E> items, Predicate<? super E> predicate) {
Iterator<E> iter = items.iterator();
while (iter.hasNext()) {
E item = iter.next();
if (predicate.test(item)) {
iter.remove();
return item;
}
}
return null; // or throw an exception
}
You can do this in two steps.您可以分两步完成此操作。 First, iterate(or stream) the list and filter the elements that satisfy your condition.
首先,迭代(或流式传输)列表并过滤满足您条件的元素。 Then remove them all from the list.
然后将它们全部从列表中删除。
List<String> elementsToBeRemoved = tests.stream()
.filter(test -> test.getId().equals(id))
.collect(Collectors.toList());
tests.removeAll(elementsToBeRemoved);
If you want to remove the first matching element or when you know for sure only one will match, you can do lile,如果你想删除第一个匹配的元素,或者当你确定只有一个匹配时,你可以这样做,
Optional<String> elementToBeRemoved = tests.stream()
.filter(test -> test.getId().equals(id))
.findFirst();
elementToBeRemoved.ifPresent(tests::remove);
Just use ArrayList.contains(desiredElement).只需使用 ArrayList.contains(desiredElement)。 For example, if you're looking for the conta1 account from your example, you could use something like:
例如,如果您要从您的示例中查找 conta1 帐户,您可以使用如下内容:
Edit: Note that in order for this to work, you will need to properly override the equals() and hashCode() methods.编辑:请注意,为了使其工作,您需要正确覆盖 equals() 和 hashCode() 方法。 If you are using Eclipse IDE, then you can have these methods generated by first opening the source file for your CurrentAccount object and the selecting Source > Generate hashCode() and equals()...
如果您使用的是 Eclipse IDE,那么您可以通过首先打开 CurrentAccount object 的源文件并选择 Source > Generate hashCode() and equals()... 来生成这些方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.