简体   繁体   English

Java如何从嵌套数组列表中删除项目

[英]Java How to remove item from nested Array List

I have a nested ArrayList as below with boolean values. 我有一个嵌套的ArrayList与布尔值如下。 I want to remove for example 3rd item from all the rows. 我想从所有行中删除例如第3个项目。 I tried with a loop but it doesnt resolve remove as a method. 我尝试了一个循环,但它不能解决remove作为一种方法的问题。 How should I do this? 我应该怎么做? Many thanks for your help. 非常感谢您的帮助。

for (int i = 0; i < list.size(); i++){
     list.get(i).remove(3)// this remove method shows as an error in IDE
 }

true    false   true    false   false   false
false   false   true    false   true    true

... It's a list of List<Instance> listInstances = new ArrayList<Instance>(); ...这是List<Instance> listInstances = new ArrayList<Instance>(); and the class Instance has vals = new ArrayList<Boolean>(); 并且类Instance具有vals = new ArrayList<Boolean>(); .... ....

In this case your solution can look like : 在这种情况下,您的解决方案可能如下所示:

public static Instance deleleNthElement(Instance instance, int index) {
    instance.getVals().remove(index - 1);
    return instance;
}

then with stream you can call the method like so : 然后使用流,您可以像这样调用方法:

int index = 3;
listInstances = listInstances.stream()
          .map(instance -> deleleNthElement(instance, index))
          .collect(Collectors.toList());

I see no error in your logic, I believe you are missing a ';' 我认为您的逻辑没有错误,我相信您缺少';' from the end of the remove(3). 从remove(3)的末尾开始。
By the way, List is an Interface, you will need to instanciate as an ArrayList (or some such). 顺便说一句,List是一个接口,您将需要实例化为ArrayList(或类似的对象)。

I strung the following together, seems to do what you intended: 我将以下内容串在一起,似乎按照您的意图去做:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {

    public static void main(String[] args) throws IOException {

        List<Boolean> row1 = new ArrayList<Boolean>(Arrays.asList(new Boolean[] {true,false,true,true}));
        List<Boolean> row2 = new ArrayList<Boolean>(Arrays.asList(new Boolean[] {true,true,false,true}));
        List<List<Boolean>> list = Arrays.asList(new ArrayList[] {(ArrayList) row1, (ArrayList) row2});

        for (int i=0;i<list.size();i++){
            list.get(i).remove(3);// this remove method shows as an error in IDE
        }
        for (List<Boolean> ll : list) {
            for (Boolean l : ll) {
                System.out.print(l + ",");
            }
            System.out.println();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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