从列表中移除一个项目并返回该项目。

huangapple go评论87阅读模式
英文:

Remove an item from a list and return the item

问题

我有一个ArrayList,我想检查列表中是否存在一个元素,如果存在,我想将其删除并返回它。

我尝试使用removeIf,但它返回一个boolean值。

我该怎么做?

谢谢!

LE

我有一个对象Test的列表:

private static List<Test> tests = new ArrayList<>();

我有一个方法public Test deleteById(long id) {}

我想要的是检查tests是否包含一个带有id的测试,如果是这样,我想要删除该对象并返回它。

英文:

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&lt;Test&gt; tests = new ArrayList&lt;&gt;();

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.

答案1

得分: 2

以下是翻译好的代码部分:

如果您想通过某个特定的条件谓词查找元素然后将其移除并返回可以使用以下方法

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; // 或者抛出异常
}
英文:

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 &lt;E&gt; E findRemoveAndReturn(List&lt;E&gt; items, Predicate&lt;? super E&gt; predicate) {
    Iterator&lt;E&gt; iter = items.iterator();
    while (iter.hasNext()) {
        E item = iter.next();
        if (predicate.test(item)) {
            iter.remove();
            return item;
        }
    }
    return null; // or throw an exception
}

答案2

得分: 1

你可以分为两个步骤完成此操作。首先,迭代(或流式处理)列表并过滤满足条件的元素。然后从列表中移除它们。

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);
英文:

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&lt;String&gt; elementsToBeRemoved = tests.stream()
        .filter(test -&gt; 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&lt;String&gt; elementToBeRemoved = tests.stream()
        .filter(test -&gt; test.getId().equals(id))
        .findFirst();
elementToBeRemoved.ifPresent(tests::remove);

答案3

得分: -1

只需使用ArrayList.contains(desiredElement)。例如,如果您正在寻找示例中的conta1账户,您可以使用类似以下的方法:

编辑:请注意,为使此方法有效,您需要正确重写equals()和hashCode()方法。如果您使用Eclipse IDE,可以通过首先打开CurrentAccount对象的源文件,然后选择Source > Generate hashCode()和equals()来生成这些方法。

英文:

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()...

huangapple
  • 本文由 发表于 2020年7月29日 02:44:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63140834.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定