如何从Java的嵌套列表中移除特定元素?

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

How to remove specific element from a list of list in java?

问题

我使用循环和深拷贝从列表中的列表中移除了特定元素。是否有其他方法可以从列表中的列表中移除特定元素?

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

public class HelloWorld {

    public static void main(String []args){
        List<ArrayList<String>> listA = new ArrayList<ArrayList<String>>();
        ArrayList<String> list1 = new ArrayList<String>();
        list1.add("cucumber");
        ArrayList<String> list2 = new ArrayList<String>();
        list2.add("carrot");
        ArrayList<String> list3 = new ArrayList<String>();
        list3.add("spinach");
        ArrayList<String> list4 = new ArrayList<String>();
        list4.add("kale");
        listA.add(list1);
        listA.add(list2);
        listA.add(list3);
        listA.add(list4);
        System.out.println("原始列表-->" + listA);

        List<List<String>> deepCopyOfListA = new ArrayList<List<String>>(listA);
        System.out.println("深拷贝列表-->" + deepCopyOfListA);

        Iterator<ArrayList<String>> itr = listA.iterator();
        while(itr.hasNext()) {
            List<String> item = itr.next();
            if ((item.contains("kale") || item.contains("cucumber"))) {
                itr.remove();
            }
        }
        System.out.println("最终列表-->" + listA);
    }
}

从下面的答案中,这似乎是最方便的方法。使用迭代器通过条件语句删除所需的元素。经过测试,效果很好。谢谢大家的建议。

Iterator<ArrayList<String>> itr = listA.iterator();
while(itr.hasNext()) {
    List<String> item = itr.next();
    if ((item.contains("cucumber") || item.contains("kale"))) {
        itr.remove();
    }
}
英文:

I removed specific element from list of list using for loop and making deepCopy. Is there any other way to remove specific element from List of List?

import java.util.ArrayList;
import java.util.List;
public class HelloWorld{
public static void main(String []args){
List&lt;ArrayList&lt;String&gt;&gt; listA = new ArrayList&lt;ArrayList&lt;String&gt;&gt;();
ArrayList&lt;String&gt; list1 = new ArrayList&lt;String&gt;();
list1.add(&quot;cucumber&quot;);
ArrayList&lt;String&gt; list2 = new ArrayList&lt;String&gt;();
list2.add(&quot;carrot&quot;);
ArrayList&lt;String&gt; list3 = new ArrayList&lt;String&gt;();
list3.add(&quot;spinach&quot;);
ArrayList&lt;String&gt; list4 = new ArrayList&lt;String&gt;();
list4.add(&quot;kale&quot;);
listA.add(list1);
listA.add(list2);
listA.add(list3);
listA.add(list4);
System.out.println(&quot;Original--&gt;&quot;+listA);
List&lt;List&lt;String&gt;&gt; deepCopyOfListA = new ArrayList&lt;List&lt;String&gt;&gt;(listA);
System.out.println(&quot;Deepcopy --&gt;&quot;+deepCopyOfListA);
for (List&lt;String&gt; item : deepCopyOfListA) {
if (item.contains(&quot;kale&quot;) || item.contains(&quot;cucumber&quot;)){
listA.remove(item);
}
}
System.out.println(&quot;Final--&gt;&quot;+listA);
}
}

From the answers below, this seemed the most convenient.
Using Iterator to remove the desired elements with if condition. Tested and it works great. Thanks everyone for your input.

Iterator&lt;ArrayList&lt;String&gt;&gt; itr = listA.iterator();
while(itr.hasNext()) {
List&lt;String&gt; item = itr.next();
if ((item.contains(&quot;cucumber&quot;) || item.contains(&quot;kale&quot;))) {
itr.remove();
}

答案1

得分: 0

截至于 [tag:java-8],如果您想从内部列表中删除特定元素,您首先必须迭代外部列表,然后在内部列表上使用 List::removeIf 方法:

// 修改原始列表
List<List<String>> outerList = ...            
for (List<String> innerList : outerList) {
    innerList.removeIf(item -> "cucumber".equals(item));
}

// 创建一个新列表,同时保持原始列表不变
List<List<String>> newList = outerList.stream()
    .map(innerList -> innerList.stream()
        .filter(item -> !"cucumber".equals(item))
        .collect(Collectors.toList()))
    .collect(Collectors.toList());

对于低于版本 8 的情况,您应该使用适当的 Iterator 方法来进行删除:

for (final List<String> innerList: outerList) {
    Iterator<String> iterator = innerList.iterator();
    while (iterator.hasNext()) {
        if ("cucumber".equals(item)) {
            iterator.remove();
        }
    }
}

无论哪种情况,都应该使用 &quot;cucumber&quot;.equals(item) 而不是 item.equals(&quot;cucumber&quot;),因为前者对 null 值更友好。

英文:

As of [tag:java-8], if you want to remove a certain element from the inner list, you have to first iterate the outer one and then use List::removeIf to the inner one:

// Mutates the original list
List&lt;List&lt;String&gt;&gt; outerList = ...            
for (List&lt;String&gt; innerList : outerList) {
innerList.removeIf(item -&gt; &quot;cucumber&quot;.equals(item));
}
// Creates a new one while keeping the original untouched
List&lt;List&lt;String&gt;&gt; newList = outerList.stream()
.map(innerList -&gt; innerList.stream()
.filter(item -&gt; !&quot;cucumber&quot;.equals(item))
.collect(Collectors.toList()))
.collect(Collectors.toList());

For the lower versions than 8, you should use a proper removal way using Iterator:

for (final List&lt;String&gt; innerList: outerList) {
Iterator&lt;String&gt; iterator = innerList.iterator();
while (iterator.hasNext()) {
if (&quot;cucumber&quot;.equals(item)) {
iterator .remove();
}
}
}

In any case, use &quot;cucumber&quot;.equals(item) rather than item.equals(&quot;cucumber&quot;) because the former one is null-friendly.

答案2

得分: 0

你可以通过迭代列表来从列表的列表中删除“cucumber”。无需创建显式的迭代器对象,也无需使用奇怪的“stream”语法。也不需要创建副本 - 深层或浅层。当然,你可能仍然想要创建副本,这样你仍然拥有原始值 - 但这取决于你。

List<List<String>> ListA = response.path("response.A");
for (List<String> item : ListA) {
    item.remove("cucumber");
}

请注意,如果任何一个列表恰好包含多个“cucumber”,这将只会删除第一个。

英文:

You can remove "cucumber" from the list of lists just by iterating the list. No need to create explicit iterator objects, no need to use the weird "stream" syntax. No need to create a copy either - deep or shallow. Of course, you may want to create a copy anyway, so that you still have the original values - but that's up to you.

List&lt;List&lt;String&gt;&gt; ListA=response.path(&quot;response.A&quot;);
for (List&lt;String&gt; item : ListA) {
item.remove(&quot;cucumber&quot;);
}

Note that if any of the lists happen to contain more than one cucumber, this will remove only the first one.

答案3

得分: 0

deepCopyofListA.removeAll(
    listA.stream()
         .filter(innerList -> innerList.stream()
                                      .anyMatch(str -> str.contains("cucumber")))
         .collect(Collectors.toList())
);

Also want to attract your attention, that according to Java Code Convention you should name your variables with lowercase (camel case, in fact). So, listA and deepCopyofListA.
英文:
DeepCopyOfListA.removeAll(
ListA.stream()
.filter(innerList -&gt; innerList.stream()
.anyMatch(str -&gt; str.contains(&quot;cucumber&quot;)))
.collect(Collectors.toList())
);

Also want to attract your attention, that according to Java Code Convention you should name your variables with lowercase (camel case, in fact). So, listA and deepCopyofListA.

答案4

得分: 0

以下是翻译好的部分:

要删除包含字符串 cucumber 的完整内部列表(即 item):

public void removeSpecificElement(Response response) {
    List<List<String>> listA = response.path("response.A");
    Iterator<List<String>> itr = listA.iterator();
    while(itr.hasNext()) {
        List<String> item = itr.next();
        if (item.contains("cucumber")) {
            itr.remove();
        }
    }
}

要仅从内部列表(即 item)中删除字符串 cucumber

public void removeSpecificElement(Response response) {
    List<List<String>> listA = response.path("response.A");
    for (List<String> item : listA) {
        item.removeAll(Collections.singleton("cucumber"));
    }
}
英文:

It is not clear whether you want to remove the complete inner list (i.e. item) if it has the string, cucumber -OR- you want to remove just the string, cucumber from the inner lists (i.e. items). Given below are solutions for each of these scenarios.

To remove the complete inner list (i.e. item) if it has the string cucumber:

public void removeSpecificElement(Response response) {
List&lt;List&lt;String&gt;&gt; listA = response.path(&quot;response.A&quot;);
Iterator&lt;List&lt;String&gt;&gt; itr = listA.iterator();
while(itr.hasNext()) {
List&lt;String&gt; item = itr.next();
if (item.contains(&quot;cucumber&quot;)) {
itr.remove();
}
}
}

To remove just the string, cucumber from the inner list (i.e. item):

public void RremoveSpecificElement(Response response) {
List&lt;List&lt;String&gt;&gt; listA = response.path(&quot;response.A&quot;);
for (List&lt;String&gt; item : listA) {
item.removeAll(Collections.singleton(&quot;cucumber&quot;));
}
}

huangapple
  • 本文由 发表于 2020年4月10日 22:16:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/61142196.html
匿名

发表评论

匿名网友

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

确定