【问题标题】:Adding elements to a collection during iteration在迭代期间向集合中添加元素
【发布时间】:2016-02-26 13:55:37
【问题描述】:

是否可以在迭代集合时将元素添加到集合中?

更具体地说,我想迭代一个集合,如果一个元素满足某个条件,我想向集合中添加一些其他元素,并确保这些添加的元素也被迭代。 (我意识到这可能导致无限循环,但我很确定在我的情况下不会。)

来自 Sun 的 Java Tutorial 表明这是不可能的:“请注意,Iterator.remove 是唯一在迭代期间修改集合的安全方法;如果基础集合被修改,则行为未指定在迭代过程中以任何其他方式进行。”

如果我不能使用迭代器做我想做的事,你建议我怎么做?

【问题讨论】:

    标签: java iterator


    【解决方案1】:

    我知道它已经很老了。但想到它对其他人有任何用处。最近我遇到了这个类似的问题,我需要一个在迭代期间可修改的队列。我使用 listIterator 在与 Avi 建议的相同的行中实现了相同的功能 -> Avi's Answer。看看这是否适合您的需要。

    ModifyWhileIterateQueue.java

    import java.util.ArrayList;
    import java.util.List;
    import java.util.ListIterator;
    
    public class ModifyWhileIterateQueue<T> {
            ListIterator<T> listIterator;
            int frontIndex;
            List<T> list;
    
            public ModifyWhileIterateQueue() {
                    frontIndex = 0;
                    list =  new ArrayList<T>();
                    listIterator = list.listIterator();
            }
    
            public boolean hasUnservicedItems () {
                    return frontIndex < list.size();  
            }
    
            public T deQueue() {
                    if (frontIndex >= list.size()) {
                            return null;
                    }
                    return list.get(frontIndex++);
            }
    
            public void enQueue(T t) {
                    listIterator.add(t); 
            }
    
            public List<T> getUnservicedItems() {
                    return list.subList(frontIndex, list.size());
            }
    
            public List<T> getAllItems() {
                    return list;
            }
    }
    

    ModifyWhileIterateQueueTest.java

        @Test
        public final void testModifyWhileIterate() {
                ModifyWhileIterateQueue<String> queue = new ModifyWhileIterateQueue<String>();
                queue.enQueue("one");
                queue.enQueue("two");
                queue.enQueue("three");
    
                for (int i=0; i< queue.getAllItems().size(); i++) {
                        if (i==1) {
                                queue.enQueue("four");
                        }
                }
    
                assertEquals(true, queue.hasUnservicedItems());
                assertEquals ("[one, two, three, four]", ""+ queue.getUnservicedItems());
                assertEquals ("[one, two, three, four]", ""+queue.getAllItems());
                assertEquals("one", queue.deQueue());
    
        }
    

    【讨论】:

      【解决方案2】:

      如下使用ListIterator:

      List<String> l = new ArrayList<>();
      l.add("Foo");
      ListIterator<String> iter = l.listIterator(l.size());
      while(iter.hasPrevious()){
          String prev=iter.previous();
          if(true /*You condition here*/){
              iter.add("Bah");
              iter.add("Etc");
          }
      }
      

      关键是要以reverse 的顺序进行迭代——然后添加的元素出现在下一次迭代中。

      【讨论】:

        【解决方案3】:

        尽管我们不能在迭代过程中将项目添加到同一个列表中,但我们可以使用 Java 8 的 flatMap 将新元素添加到流中。这可以在一个条件下完成。在此之后可以处理添加的项目。

        这是一个 Java 示例,它展示了如何根据条件将对象添加到正在进行的流中,然后使用条件进行处理:

        List<Integer> intList = new ArrayList<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        
        intList = intList.stream().flatMap(i -> {
            if (i == 2) return Stream.of(i, i * 10); // condition for adding the extra items
            return Stream.of(i);
        }).map(i -> i + 1)
                .collect(Collectors.toList());
        
        System.out.println(intList);
        

        玩具示例的输出是:

        [2, 3, 21, 4]

        【讨论】:

          【解决方案4】:

          例如,我们有两个列表:

            public static void main(String[] args) {
                  ArrayList a = new ArrayList(Arrays.asList(new String[]{"a1", "a2", "a3","a4", "a5"}));
                  ArrayList b = new ArrayList(Arrays.asList(new String[]{"b1", "b2", "b3","b4", "b5"}));
                  merge(a, b);
                  a.stream().map( x -> x + " ").forEach(System.out::print);
              }
             public static void merge(List a, List b){
                  for (Iterator itb = b.iterator(); itb.hasNext(); ){
                      for (ListIterator it = a.listIterator() ; it.hasNext() ; ){
                          it.next();
                          it.add(itb.next());
          
                      }
                  }
          
              }
          

          a1 b1 a2 b2 a3 b3 a4 b4 a5 b5

          【讨论】:

            【解决方案5】:

            这是我通常做的,集合之类的:

            Set<T> adds = new HashSet<T>, dels = new HashSet<T>;
            for ( T e: target )
              if ( <has to be removed> ) dels.add ( e );
              else if ( <has to be added> ) adds.add ( <new element> )
            
            target.removeAll ( dels );
            target.addAll ( adds );
            

            这会创建一些额外的内存(中间集的指针,但不会发生重复的元素)和额外的步骤(再次迭代更改),但是通常这没什么大不了的,它可能比使用初始值更好收藏副本。

            【讨论】:

              【解决方案6】:

              这里有两个问题:

              第一个问题是,在返回 Iterator 后添加到 Collection。如前所述,当底层Collection 被修改时,没有定义的行为,如Iterator.remove 的文档中所述:

              ... 迭代器的行为是 未指定,如果基础 集合被修改,而 迭代正在以任何方式进行 除了调用这个方法。

              第二个问题是,即使可以得到Iterator,然后返回到Iterator所在的同一个元素,也不能保证迭代的顺序,如Collection.iterator中所述方法文档:

              ... 不保证 元素的顺序 返回(除非此集合是 提供了一个类的实例 保证)。

              例如,假设我们有列表[1, 2, 3, 4]。

              假设Iterator 位于3 时添加了5,不知何故,我们得到了一个Iterator,它可以从4 恢复迭代。但是,不能保证5 将在4 之后出现。迭代顺序可能是[5, 1, 2, 3, 4]——那么迭代器仍然会错过元素5。

              由于无法保证行为,因此不能假设事情会以某种方式发生。

              另一种选择是有一个单独的Collection,可以将新创建​​的元素添加到其中,然后迭代这些元素:

              Collection<String> list = Arrays.asList(new String[]{"Hello", "World!"});
              Collection<String> additionalList = new ArrayList<String>();
              
              for (String s : list) {
                  // Found a need to add a new element to iterate over,
                  // so add it to another list that will be iterated later:
                  additionalList.add(s);
              }
              
              for (String s : additionalList) {
                  // Iterate over the elements that needs to be iterated over:
                  System.out.println(s);
              }
              

              编辑

              详细说明Avi's answer,可以将我们想要迭代的元素排队到队列中,并在队列中有元素时删除元素。这将允许在原始元素之外对新元素进行“迭代”。

              让我们看看它是如何工作的。

              从概念上讲,如果我们在队列中有以下元素:

              [1, 2, 3, 4]

              而且,当我们删除1,我们决定添加42,队列如下:

              [2, 3, 4, 42]

              由于队列是FIFO(先进先出)数据结构,这种排序是典型的。 (正如Queue 接口的文档中所述,这不是Queue 的必要条件。以PriorityQueue 为例,它按照元素的自然顺序对元素进行排序,所以这不是FIFO。)

              以下是使用LinkedList(即Queue)的示例,以便遍历所有元素以及在出队期间添加的其他元素。与上例类似,当元素2被移除时,元素42被添加:

              Queue<Integer> queue = new LinkedList<Integer>();
              queue.add(1);
              queue.add(2);
              queue.add(3);
              queue.add(4);
              
              while (!queue.isEmpty()) {
                  Integer i = queue.remove();
                  if (i == 2)
                      queue.add(42);
              
                  System.out.println(i);
              }
              

              结果如下:

              1
              2
              3
              4
              42
              

              正如所愿,我们点击2时添加的元素42出现了。

              【讨论】:

              • 我认为 Avi 的观点是,如果你有一个队列,你就不需要遍历它。您只需在它不为空时从前面出列元素,然后将新元素入列到后面。
              • @Nat:你说得对,谢谢你指出这一点。我已经编辑了我的答案以反映这一点。
              • @coobird 出于某种原因,您的答案被截断了。 [...] 为了遍历所有元素以及其他 el- 这就是我能看到的全部内容,但是如果我尝试编辑答案,一切都在那里。知道发生了什么吗?
              【解决方案7】:

              我厌倦了 ListIterator 但它对我的情况没有帮助,您必须在添加列表时使用列表。这对我有用:

              使用 LinkedList。

              LinkedList<String> l = new LinkedList<String>();
              l.addLast("A");
              
              while(!l.isEmpty()){
                  String str = l.removeFirst();
                  if(/* Condition for adding new element*/)
                      l.addLast("<New Element>");
                  else
                      System.out.println(str);
              }
              

              这可能会引发异常或陷入无限循环。但是,正如您所提到的

              我很确定在我的情况下不会

              检查此类代码中的极端情况是您的责任。

              【讨论】:

                【解决方案8】:

                忘记迭代器,它们不能用于添加,只能用于删除。我的回答只适用于列表,所以不要因为我没有解决收藏问题而惩罚我。坚持基础:

                    List<ZeObj> myList = new ArrayList<ZeObj>();
                    // populate the list with whatever
                            ........
                    int noItems = myList.size();
                    for (int i = 0; i < noItems; i++) {
                        ZeObj currItem = myList.get(i);
                        // when you want to add, simply add the new item at last and
                        // increment the stop condition
                        if (currItem.asksForMore()) {
                            myList.add(new ZeObj());
                            noItems++;
                        }
                    }
                

                【讨论】:

                • 谢谢斯特凡。修好了。
                【解决方案9】:

                给定一个列表List&lt;Object&gt;,您想对其进行迭代,简单的方法是:

                while (!list.isEmpty()){
                   Object obj = list.get(0);
                
                   // do whatever you need to
                   // possibly list.add(new Object obj1);
                
                   list.remove(0);
                }
                

                所以,你遍历一个列表,总是取第一个元素,然后删除它。这样,您可以在迭代时将新元素附加到列表中。

                【讨论】:

                  【解决方案10】:
                  public static void main(String[] args)
                  {
                      // This array list simulates source of your candidates for processing
                      ArrayList<String> source = new ArrayList<String>();
                      // This is the list where you actually keep all unprocessed candidates
                      LinkedList<String> list = new LinkedList<String>();
                  
                      // Here we add few elements into our simulated source of candidates
                      // just to have something to work with
                      source.add("first element");
                      source.add("second element");
                      source.add("third element");
                      source.add("fourth element");
                      source.add("The Fifth Element"); // aka Milla Jovovich
                  
                      // Add first candidate for processing into our main list
                      list.addLast(source.get(0));
                  
                      // This is just here so we don't have to have helper index variable
                      // to go through source elements
                      source.remove(0);
                  
                      // We will do this until there are no more candidates for processing
                      while(!list.isEmpty())
                      {
                          // This is how we get next element for processing from our list
                          // of candidates. Here our candidate is String, in your case it
                          // will be whatever you work with.
                          String element = list.pollFirst();
                          // This is where we process the element, just print it out in this case
                          System.out.println(element);
                  
                          // This is simulation of process of adding new candidates for processing
                          // into our list during this iteration.
                          if(source.size() > 0) // When simulated source of candidates dries out, we stop
                          {
                              // Here you will somehow get your new candidate for processing
                              // In this case we just get it from our simulation source of candidates.
                              String newCandidate = source.get(0);
                              // This is the way to add new elements to your list of candidates for processing
                              list.addLast(newCandidate);
                              // In this example we add one candidate per while loop iteration and 
                              // zero candidates when source list dries out. In real life you may happen
                              // to add more than one candidate here:
                              // list.addLast(newCandidate2);
                              // list.addLast(newCandidate3);
                              // etc.
                  
                              // This is here so we don't have to use helper index variable for iteration
                              // through source.
                              source.remove(0);
                          }
                      }
                  }
                  

                  【讨论】:

                    【解决方案11】:

                    其实很简单。只考虑最佳方式。 我相信最佳方法是:

                    for (int i=0; i<list.size(); i++) {
                       Level obj = list.get(i);
                    
                       //Here execute yr code that may add / or may not add new element(s)
                       //...
                    
                       i=list.indexOf(obj);
                    }
                    

                    以下示例在最合乎逻辑的情况下完美运行 - 当您不需要在迭代元素之前迭代添加的新元素时。关于迭代元素之后添加的元素 - 您可能也不想迭代它们。在这种情况下,您应该简单地添加/或扩展 yr 对象,并使用一个标志将它们标记为不对其进行迭代。

                    【讨论】:

                    • 添加时不需要 indexOf,如果有重复项可能会造成混淆。
                    • 是的,确实,重复是个问题。感谢您添加。
                    • 应该补充一点,根据实际的列表实现,list.get(i) 可能比使用迭代器更昂贵。至少对于较大的链表,可能会有相当大的性能损失,例如)
                    【解决方案12】:

                    除了使用附加列表并调用 addAll 以在迭代后插入新项目的解决方案(例如用户 Nat 的解决方案)之外,您还可以使用并发集合,如 CopyOnWriteArrayList。

                    “快照”样式的迭代器方法使用对创建迭代器时数组状态的引用。该数组在迭代器的生命周期内永远不会改变,因此不可能发生干扰,并且保证迭代器不会抛出 ConcurrentModificationException。

                    使用这个特殊的集合(通常用于并发访问),可以在对底层列表进行迭代时对其进行操作。但是,迭代器不会反映更改。

                    这比其他解决方案更好吗?可能不会,我不知道 Copy-On-Write 方法引入的开销。

                    【讨论】:

                      【解决方案13】:

                      恕我直言,更安全的方法是创建一个新集合,遍历给定集合,在新集合中添加每个元素,并根据需要在新集合中添加额外元素,最后返回新集合。

                      【讨论】:

                        【解决方案14】:

                        我更喜欢按功能处理集合,而不是就地改变它们。这完全避免了此类问题,以及别名问题和其他棘手的错误来源。

                        所以,我会像这样实现它:

                        List<Thing> expand(List<Thing> inputs) {
                            List<Thing> expanded = new ArrayList<Thing>();
                        
                            for (Thing thing : inputs) {
                                expanded.add(thing);
                                if (needsSomeMoreThings(thing)) {
                                    addMoreThingsTo(expanded);
                                }
                            }
                        
                            return expanded;
                        }
                        

                        【讨论】:

                          【解决方案15】:

                          使用迭代器...不,我不这么认为。你必须像这样拼凑出一些东西:

                              Collection< String > collection = new ArrayList< String >( Arrays.asList( "foo", "bar", "baz" ) );
                              int i = 0;
                              while ( i < collection.size() ) {
                          
                                  String curItem = collection.toArray( new String[ collection.size() ] )[ i ];
                                  if ( curItem.equals( "foo" ) ) {
                                      collection.add( "added-item-1" );
                                  }
                                  if ( curItem.equals( "added-item-1" ) ) {
                                      collection.add( "added-item-2" );
                                  }
                          
                                  i++;
                              }
                          
                              System.out.println( collection );
                          

                          哪个产量:
                          [foo, bar, baz, added-item-1, added-item-2]

                          【讨论】:

                            【解决方案16】:

                            您可能还想查看一些更专业的类型,例如ListIterator、NavigableSet 和(如果您对地图感兴趣)NavigableMap。

                            【讨论】:

                              【解决方案17】:

                              在一般中,这是不安全的,但对于某些集合来说可能是安全的。显而易见的替代方法是使用某种 for 循环。但是你没有说你使用的是什么集合,所以这可能也可能不可能。

                              【讨论】:

                                【解决方案18】:

                                如何使用要迭代的元素构建一个队列;当你想添加元素时,将它们排在队列的末尾,并继续删除元素,直到队列为空。这就是广度优先搜索通常的工作方式。

                                【讨论】:

                                • 如果它适合 OP 编码的模型,这是一种很好的做事方式。这样你就不用使用迭代器——只是一个 while 循环。当队列中有元素时,处理第一个元素。不过,您也可以使用 List 来做到这一点。
                                • ListIterator iter = list.listIterator() 同时拥有add() 和remove() 方法,因此您可以在迭代过程中添加和删除元素
                                • @soulmachine 你确定吗?如果我尝试这样做,我会得到 ConcurrentModificationException。
                                • 我认为你是对的,但还有另一种选择,使用线程安全集合,如 LinkedBlockingQueue
                                • 对于那些在使用 ListIterator 时遇到 ConcurrentModificationException 的人 (@NiekeAerts):您必须在 ListIterator 上使用 remove() 和 add() 方法,而不是在 List 上。跨度>
                                猜你喜欢
                                • 1970-01-01
                                • 2021-10-15
                                • 2017-08-17
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 2022-12-18
                                相关资源
                                最近更新 更多