【问题标题】:How to keep certain values in an ArrayList and remove the rest?如何将某些值保留在 ArrayList 中并删除其余值?
【发布时间】:2017-04-04 04:51:57
【问题描述】:

我的 ArrayList 名为 values,我可以使用下面的代码删除字符串。 ArrayList 有字符串、负值和其他我想删除的整数,但我不能使用 remove 方法,因为我不知道所有的值。这使我无法使用下面的代码。我想保留 1 到 23 之间的所有值并删除其余值。

values.remove("O9N");

我尝试使用此方法,但它似乎不起作用。有人可以看看它并告诉我哪里出错了。

int col = 2; 
List values = new ArrayList(table.getRowCount());

for (int row = 0; row < table.getRowCount(); row++) {
values.add(table.getValueAt(row, col));
}

List<String> thingsIWantToKeep = new ArrayList<>();
if (values.contains(1)) {
String s1 ="1";
thingsIWantToKeep.add(s1);
}
if (values.contains(2)) {
String s2 ="2";
thingsIWantToKeep.add(s2);
}
System.out.println(thingsIWantToKeep);

因此,如果列表值中有 1,它应该将值 1 添加到 thingsIWantToKeep,但即使列表值有 1 个 init,它也只会打印出空白。

【问题讨论】:

  • 您在上一个问题中提供的答案有什么问题?在该代码中,如果它不符合要求,则不将其添加到列表中是有意义的
  • 用你想保留的值创建另一个ArrayList,然后在原始列表上调用ArrayList#retainAll,传入另一个
  • 如果要删除元素,最好使用迭代器。

标签: java string arraylist


【解决方案1】:

List#retainAll“仅保留此列表中包含在指定集合中的元素”

List<String> thingsIHave = new ArrayList<>(25);
//...
List<String> thingsIWantToKeep = new ArrayList<>(25);
for (int index = 1; index < 24; index++) {
    thingsIWantToKeep.add(Integer.toString(index));
}
thingsIHave.retainAll(thingsIWantToKeep);

【讨论】:

  • 嘿,还有一个问题,我用了` if (thingsIHave.contains(1)){ String s1 ="1"; thingsIWantToKeep.add(s1);}`arraylist thingsIHave 的值为 1,但 thingsIWantToKeep arrylist 仍然没有添加 1。知道为什么吗?
  • 如果你通过它 thingsIHave.contains 返回 true 987654326@
  • 我已经编辑了我的问题并添加了代码。请你看一下好吗
【解决方案2】:

创建包含要删除的元素的 ArrayList 并调用 removeAll 方法:

list.removeAll(listToRemove);

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    相关资源
    最近更新 更多