[英]Remove an item from a list and return the item
我有一個ArrayList
,我想檢查列表中是否存在某個元素,如果存在,我想將其刪除並返回。
我嘗試使用removeIf
但它返回boolean
值。
我怎樣才能做到這一點?
謝謝!
樂
我有一個對象列表測試:
private static List<Test> tests = new ArrayList<>();
我有方法public Test deleteById(long id) {}
。
我想要的是檢查tests
是否包含帶有id
的測試,如果是,我想刪除 object 並返回它。
如果你想通過某個謂詞找到一個元素,刪除它並返回它,你可以有這樣的方法:
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
}
您可以分兩步完成此操作。 首先,迭代(或流式傳輸)列表並過濾滿足您條件的元素。 然后將它們全部從列表中刪除。
List<String> elementsToBeRemoved = tests.stream()
.filter(test -> test.getId().equals(id))
.collect(Collectors.toList());
tests.removeAll(elementsToBeRemoved);
如果你想刪除第一個匹配的元素,或者當你確定只有一個匹配時,你可以這樣做,
Optional<String> elementToBeRemoved = tests.stream()
.filter(test -> test.getId().equals(id))
.findFirst();
elementToBeRemoved.ifPresent(tests::remove);
只需使用 ArrayList.contains(desiredElement)。 例如,如果您要從您的示例中查找 conta1 帳戶,您可以使用如下內容:
編輯:請注意,為了使其工作,您需要正確覆蓋 equals() 和 hashCode() 方法。 如果您使用的是 Eclipse IDE,那么您可以通過首先打開 CurrentAccount object 的源文件並選擇 Source > Generate hashCode() and equals()... 來生成這些方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.