在arrayList迭代过程中添加元素(添加到列表的final)

时间:2022-01-09 01:47:35

I want to add some elements to an arrayList during iteraction, but I want to add in the final of the list, I have tried with ListIterator but only adds after the actual element on interaction...

我想在iteraction过程中向arrayList添加一些元素,但我想在列表的最后添加一些元素,我尝试了ListIterator,但只在实际的交互元素之后添加……

Example:

例子:

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5}));      
for (ListIterator<Integer> i = arr.listIterator(); i.hasNext();) {          
    i.add(i.next() + 10);               
}       
System.out.println(arr);

That prints: [1, 11, 2, 12, 3, 13, 4, 14, 5, 15]

指纹:[1,11,2,12,3,13,4,14,5,15]

What I have to do to get: [1, 2, 3, 4, 5, 11, 12, 13, 14, 15] ?

我要做什么才能得到:[1、2、3、4、5、11、12、13、14、15]?

My problem cannot be solved creating another list and using addAll() after... My explanation of the problem was poor, let me explain better:

我的问题不能解决创建另一个列表和使用addAll()之后…我对这个问题的解释很差,让我来解释一下:

ArrayList<SomeClass> arr = new ArrayList<>();               
        int condition = 12; // example contidition number   
        for (ListIterator<SomeClass> i = arr.listIterator(); i.hasNext();) {                        
            if (i.next().conditionNumber == condition) {                
                // add to final of the list to process after all elements.                                                                 
            } else {                
                // process the element.     
                // change the contidition               
                condition = 4; // another example, this number will change many times               
            }                           
        }       

I can't create a separated list because the elements add to final may enter in the condition again

我不能创建一个单独的列表,因为添加到final的元素可能再次进入条件

Thanks

谢谢

4 个解决方案

#1


4  

Since you're using Java 8, you could use the Stream API. Concat two streams of the original list, with one that maps each element by adding 10 to it.

由于使用的是Java 8,所以可以使用流API。包含原始列表的两条流,其中一条通过添加10来映射每个元素。

List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> result = Stream.concat(arr.stream(), arr.stream().map(i -> i + 10))
                             .collect(Collectors.toList());

As you updated your question, I don't see why you can't create another list that you update continuously. This is what I'd do in your case.

当您更新您的问题时,我不明白为什么您不能创建另一个您不断更新的列表。这就是我在你的情况下要做的。

Here's a solution that update the list you are iterating using an index-based for loop, but don't forget to cache the size before starting to iterate, so that you only process the elements that were in the list before the processing.

这里有一个解决方案,可以使用基于索引的for循环更新正在迭代的列表,但不要忘记在开始迭代之前缓存大小,以便在处理之前只处理列表中的元素。

ArrayList<SomeClass> arr = new ArrayList<>();
int condition = 12; // example contidition number
final int prevSize = arr.size();
for (int i = 0; i < prevSize; i++) {
    SomeClass element = arr.get(i);
    if (element.conditionNumber == condition) {
        //probably update or create a new element here
        arr.add(someNewElement);
    } else {
        // process the element.
        // change the contidition
        condition = 4; // another example, this number will change many times
    }
} 

I can't create a separated list because the elements add to final may enter in the condition again

我不能创建一个单独的列表,因为添加到final的元素可能再次进入条件

It seems to me like a dangerous behavior, that may add elements indefinitely to the list, but you probably know the real problem you are facing. If you can try to avoid this that would be better, IMO.

在我看来,这似乎是一种危险的行为,可能会无限期地将元素添加到列表中,但您可能知道您所面临的真正问题。如果你能尽量避免这种情况,那就更好了,在我看来。

#2


0  

Try:

试一试:

This is in addition to what dasblinkenlight says: as add will add to its current position. you need to use

这是dasblinkenlight所说的:as添加将增加其当前位置。您需要使用

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5}));

ArrayList<Integer> arr1 =new ArrayList<Integer>();

for (ListIterator<Integer> i = arr.listIterator(); i.hasNext();) {          
    arr1.add(i.next() + 10);               
}       

arr.addAll(arr1);
System.out.println(arr);

#3


0  

Why not using plain old for?

为什么不用plain old来做呢?

ArrayList<SomeClass> arr = new ArrayList<>();               
int condition = 12; // example contidition number
for (int i = 0; i < arr.size(); i++) {
    if (arr.get(i).conditionNumber == condition) {
        // add to final of the list to process after all elements.
        arr.add(someNewElement);
    } else {
        // process the element.
        // change the contidition
        condition = 4; // another example, this number will change many times
    }                           
}

Not so cool, but should work in your case.

不太酷,但你的情况应该可以。

#4


0  

You could use the collect method which can join two list with your customization, like the one I have done below

您可以使用collect方法,该方法可以将两个列表连接到您的定制中,就像下面我所做的那样

  List<Integer> arr = Arrays.asList(1,2,3,4,5);                                                                

  List<Integer> newList = arr.stream()                                                                         
          .collect(ArrayList<Integer>::new, (list, num) -> {                                                   
              list.add(num);                                                                                   
              list.add(num + 10);                                                                              
          }, ArrayList::addAll)       // this will give us the final list of element num and num+10            
          .stream()                                                                                            
          .sorted()                                                                                            
          .collect(Collectors.toList());                                                                       

  System.out.println(newList );      

key here is using the below variation of collect method of stream api

这里的关键是使用以下流api的收集方法的变体

collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator,BiConsumer<R, R> combiner);
Please let me know if it can solve the problem.

收集(供应商< R >供应商,BiConsumer < R,?超级T>累加器,双sumer combiner);请告诉我它是否能解决这个问题。 ,>

#1


4  

Since you're using Java 8, you could use the Stream API. Concat two streams of the original list, with one that maps each element by adding 10 to it.

由于使用的是Java 8,所以可以使用流API。包含原始列表的两条流,其中一条通过添加10来映射每个元素。

List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> result = Stream.concat(arr.stream(), arr.stream().map(i -> i + 10))
                             .collect(Collectors.toList());

As you updated your question, I don't see why you can't create another list that you update continuously. This is what I'd do in your case.

当您更新您的问题时,我不明白为什么您不能创建另一个您不断更新的列表。这就是我在你的情况下要做的。

Here's a solution that update the list you are iterating using an index-based for loop, but don't forget to cache the size before starting to iterate, so that you only process the elements that were in the list before the processing.

这里有一个解决方案,可以使用基于索引的for循环更新正在迭代的列表,但不要忘记在开始迭代之前缓存大小,以便在处理之前只处理列表中的元素。

ArrayList<SomeClass> arr = new ArrayList<>();
int condition = 12; // example contidition number
final int prevSize = arr.size();
for (int i = 0; i < prevSize; i++) {
    SomeClass element = arr.get(i);
    if (element.conditionNumber == condition) {
        //probably update or create a new element here
        arr.add(someNewElement);
    } else {
        // process the element.
        // change the contidition
        condition = 4; // another example, this number will change many times
    }
} 

I can't create a separated list because the elements add to final may enter in the condition again

我不能创建一个单独的列表,因为添加到final的元素可能再次进入条件

It seems to me like a dangerous behavior, that may add elements indefinitely to the list, but you probably know the real problem you are facing. If you can try to avoid this that would be better, IMO.

在我看来,这似乎是一种危险的行为,可能会无限期地将元素添加到列表中,但您可能知道您所面临的真正问题。如果你能尽量避免这种情况,那就更好了,在我看来。

#2


0  

Try:

试一试:

This is in addition to what dasblinkenlight says: as add will add to its current position. you need to use

这是dasblinkenlight所说的:as添加将增加其当前位置。您需要使用

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5}));

ArrayList<Integer> arr1 =new ArrayList<Integer>();

for (ListIterator<Integer> i = arr.listIterator(); i.hasNext();) {          
    arr1.add(i.next() + 10);               
}       

arr.addAll(arr1);
System.out.println(arr);

#3


0  

Why not using plain old for?

为什么不用plain old来做呢?

ArrayList<SomeClass> arr = new ArrayList<>();               
int condition = 12; // example contidition number
for (int i = 0; i < arr.size(); i++) {
    if (arr.get(i).conditionNumber == condition) {
        // add to final of the list to process after all elements.
        arr.add(someNewElement);
    } else {
        // process the element.
        // change the contidition
        condition = 4; // another example, this number will change many times
    }                           
}

Not so cool, but should work in your case.

不太酷,但你的情况应该可以。

#4


0  

You could use the collect method which can join two list with your customization, like the one I have done below

您可以使用collect方法,该方法可以将两个列表连接到您的定制中,就像下面我所做的那样

  List<Integer> arr = Arrays.asList(1,2,3,4,5);                                                                

  List<Integer> newList = arr.stream()                                                                         
          .collect(ArrayList<Integer>::new, (list, num) -> {                                                   
              list.add(num);                                                                                   
              list.add(num + 10);                                                                              
          }, ArrayList::addAll)       // this will give us the final list of element num and num+10            
          .stream()                                                                                            
          .sorted()                                                                                            
          .collect(Collectors.toList());                                                                       

  System.out.println(newList );      

key here is using the below variation of collect method of stream api

这里的关键是使用以下流api的收集方法的变体

collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator,BiConsumer<R, R> combiner);
Please let me know if it can solve the problem.

收集(供应商< R >供应商,BiConsumer < R,?超级T>累加器,双sumer combiner);请告诉我它是否能解决这个问题。 ,>