【问题标题】:How to remove element from ArrayList by checking its value?如何通过检查其值从 ArrayList 中删除元素?
【发布时间】:2012-12-23 07:00:17
【问题描述】:

我有 ArrayList,我想从中删除一个具有特定值的元素...

例如。

ArrayList<String> a=new ArrayList<String>();
a.add("abcd");
a.add("acbd");
a.add("dbca");

我知道我们可以迭代 arraylist 和 .remove() 方法来删​​除元素,但我不知道在迭代时如何做。 如何删除值为“acbd”的元素,即第二个元素?

【问题讨论】:

标签: java collections arraylist


【解决方案1】:

在您的情况下,无需遍历列表,因为您知道要删除哪个对象。你有几个选择。首先,您可以按索引删除对象(因此,如果您知道该对象是第二个列表元素):

 a.remove(1);       // indexes are zero-based

或者,您可以删除字符串的 first 出现:

 a.remove("acbd");  // removes the first String object that is equal to the
                    // String represented by this literal

或者,删除所有具有特定值的字符串:

 while(a.remove("acbd")) {}

如果您的集合中有更复杂的对象并且想要删除具有特定属性的实例,则情况会更复杂一些。这样您就无法通过将 remove 与您要删除的对象相同的对象来删除它们。

在这种情况下,我通常使用第二个列表来收集我想要删除的所有实例,并在第二遍中删除它们:

 List<MyBean> deleteCandidates = new ArrayList<>();
 List<MyBean> myBeans = getThemFromSomewhere();

 // Pass 1 - collect delete candidates
 for (MyBean myBean : myBeans) {
    if (shallBeDeleted(myBean)) {
       deleteCandidates.add(myBean);
    }
 }

 // Pass 2 - delete
 for (MyBean deleteCandidate : deleteCandidates) {
    myBeans.remove(deleteCandidate);
 }

【讨论】:

  • removeAll 需要一个集合,所以你需要这样做list.removeAll(Arrays.asList("acbd"));
  • 糟糕 ;) 我会改变它。
  • +1,List 有一个removeAll(Collection obj) 方法,所以你可以只使用myBeans.removeAll(deleteCandidates); 而不是遍历deleteCandidate 列表。
  • -1 你还没有考虑到 removeAll 的要点,遍历数组和删除看起来很可怕。特别是当您在 while 语句中有 a.remove 时。在清晰度方面的糟糕实践。
  • @Andreas_D 要添加到您的评论中,如果列表中的项目是整数类型,则您的删除方法将引发异常。例如。 Mylist=[2,3,5],尝试通过Mylist.remove(5) 删除5
【解决方案2】:

单线(java8):

list.removeIf(s -> s.equals("acbd")); // removes all instances, not just the 1st one

(所有的迭代都是隐式的)

【讨论】:

  • 还有助于删除对象,具体取决于一个属性,如下所示:list.removeIf(obj -&gt; obj.getAttribute().equals(otherObj.getAttribute()));
  • 您可以将其缩短为list.removeIf("abcd"::equals);
  • @SamuelPhilipp 如果我有对象列表怎么办?我有 list.removeIf(s -> "abcd".equals(s.getName()));
【解决方案3】:

您需要像这样使用Iterator

Iterator<String> iterator = a.iterator();
while(iterator.hasNext())
{
    String value = iterator.next();
    if ("abcd".equals(value))
    {
        iterator.remove();
        break;
    }
}

话虽如此,您可以使用ArrayList 类提供的remove(int index)remove(Object obj)。但是请注意,在您遍历循环时调用这些方法会导致 ConcurrentModificationException,因此这不起作用:

for(String str : a)
{
    if (str.equals("acbd")
    {
        a.remove("abcd");
        break;
    }
}

但这会(因为您没有迭代循环的内容):

a.remove("acbd");

如果您有更复杂的对象,则需要重写 equals 方法。

【讨论】:

  • 我会使用 "abcd".equals(value) 来避免 NullPointerExceptions,因为 List 可以包含空值。请注意,使用“break”,您仅显式删除了值为“abcd”的第一个匹配项。
  • @AdriaanKoster:是的,你是对的。我已经修改了我的答案。此外,关于中断,OP 没有提到重复元素的可能性。如果有重复,那么是的,break 需要被删除。
  • 我同意 OP 没有指定应该删除多少实例。我对问题添加了评论。
  • @AdriaanKoster:关于你的第二点,我从来没有遇到过这个问题。 a.remove(new String("acbd")) 会工作吗?
  • @AdriaanKoster:那你会怎么做呢?您在遍历所有字符串时是否对它们进行了实习?另外,感谢您的支持;)
【解决方案4】:

对于 java8,我们可以像这样简单地使用 removeIf 函数

listValues.removeIf(value -> value.type == "Deleted");

【讨论】:

    【解决方案5】:

    这些问题请查看API

    您可以使用remove 方法。

    a.remove(1);
    

    a.remove("acbd");
    

    【讨论】:

      【解决方案6】:

      这会给你输出,

          ArrayList<String> l= new ArrayList<String>();
      
          String[] str={"16","b","c","d","e","16","f","g","16","b"};
          ArrayList<String> tempList= new ArrayList<String>();
      
          for(String s:str){
              l.add(s);
          }
      
          ArrayList<String> duplicates= new ArrayList<String>();
      
          for (String dupWord : l) {
              if (!tempList.contains(dupWord)) {
                  tempList.add(dupWord);
              }else{
                  duplicates.add(dupWord);
              }
          }
      
          for(String check : duplicates){
              if(tempList.contains(check)){
                  tempList.remove(check);
              }
          }
      
          System.out.println(tempList);
      

      输出,

      [c, d, e, f, g]
      

      【讨论】:

        【解决方案7】:

        只需使用myList.remove(myObject)

        它使用类的equals方法。见http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)

        顺便说一句,如果你有更复杂的事情要做,你应该看看 guava 库,它有很多实用程序可以用谓词等来做。

        【讨论】:

          【解决方案8】:

          使用迭代器循环遍历列表,然后删除所需的对象。

              Iterator itr = a.iterator();
              while(itr.hasNext()){
                  if(itr.next().equals("acbd"))
                      itr.remove();
              }
          

          【讨论】:

            【解决方案9】:

            使用list接口中提供的contains()方法来检查list中是否存在该值。如果它包含该元素,则获取其索引并将其删除

            【讨论】:

              【解决方案10】:

              根据匹配条件从任何arraylist中删除元素的片段如下:

              List<String> nameList = new ArrayList<>();
                      nameList.add("Arafath");
                      nameList.add("Anjani");
                      nameList.add("Rakesh");
              
              Iterator<String> myItr = nameList.iterator();
              
                  while (myItr.hasNext()) {
                      String name = myItr.next();
                      System.out.println("Next name is: " + name);
                      if (name.equalsIgnoreCase("rakesh")) {
                          myItr.remove();
                      }
                  }
              

              【讨论】:

                【解决方案11】:

                试试下面的代码:

                 public static void main(String[] args) throws Exception{
                     List<String> l = new ArrayList<String>();
                     l.add("abc");
                     l.add("xyz");
                     l.add("test");
                     l.add("test123");
                     System.out.println(l);
                     List<String> dl = new ArrayList<String>();
                    for (int i = 0; i < l.size(); i++) {
                         String a = l.get(i);
                         System.out.println(a); 
                         if(a.equals("test")){
                             dl.add(a);
                         }
                    }
                    l.removeAll(dl);
                     System.out.println(l); 
                }
                

                你的输出:

                 [abc, xyz, test, test123]
                abc
                xyz
                test
                test123
                [abc, xyz, test123]
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-02-24
                  • 2023-03-27
                  • 2018-11-05
                  • 2018-07-19
                  • 1970-01-01
                  相关资源
                  最近更新 更多