简体   繁体   中英

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.

I tried to use removeIf but it returns a boolean value.

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) {} .

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.

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). For example, if you're looking for the conta1 account from your example, you could use something like:

Edit: Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. 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()...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM