Java按值删除ArrayList

时间:2017-12-19 10:12:01

标签: java arrays arraylist

我有一个像这样的ArrayList:

  

[{1 = R111,2 =红色,3 = 50000},{1 = R123,2 =蓝色,3 = 50000}]

我希望按值删除数组(R111或R123)。

如何使用array.remove方法为数组删除数组?

我试过this link 但它对我的问题不起作用。

2 个答案:

答案 0 :(得分:1)

假设您的ArrayList是:

List<String[]> arrayList = new ArrayList<>();
arrayList.add(new String[]{"R111","Red","50000"});
arrayList.add(new String[]{"R123","Blue","50000"});

你可以这样做:

for (Iterator<String[]> iterator = arrayList.iterator();iterator.hasNext();) {
    String[] stringArray = iterator.next();
    if("R111".equals(stringArray[0])) {
        iterator.remove();
    }
}

您可以在迭代iterator.remove()时使用ArrayList安全地删除元素。另请参阅The collection Interface

使用Streams的另一种更短的方法是:

Optional<String[]> array = arrayList.stream().filter(a -> "R111".equals(a[0])).findFirst();
array.ifPresent(strings -> arrayList.remove(strings));

答案 1 :(得分:1)

感谢pieter,我使用了Iterator:

for (Iterator<HashMap<String, String>> iterator = RegulerMenu.iterator(); iterator.hasNext();) {
    HashMap<String, String> stringArray = iterator.next();
            if("R111".equals(stringArray.get("1"))) {
                iterator.remove();
            }
        }

现在正在工作,非常感谢你。