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

问题描述 投票:1回答:3

我有一个嵌套的ArrayList,如下所示,带有布尔值。我想删除所有行中的第3项。我尝试了一个循环,但它没有解决remove作为一种方法。我该怎么做?非常感谢您的帮助。

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
java list nested nested-lists
3个回答
2
投票

...这是一个List<Instance> listInstances = new ArrayList<Instance>();列表和类Instancevals = new ArrayList<Boolean>(); ....

在这种情况下,您的解决方案看起来像:

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

然后使用流你可以像这样调用方法:

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

2
投票

我认为你的逻辑没有错误,我相信你错过了';'从删除结束(3)。 顺便说一下,List是一个接口,你需要将其作为一个ArrayList(或者其他类似的东西)进行实例化。


1
投票

我将以下内容串起来,似乎按照你的意图行事:

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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.