java - Add element during arrayList iteraction (add to final of the list) -
i want add elements arraylist during iteraction, want add in final of list, have tried listiterator adds after actual element on interaction...
example:
arraylist<integer> arr = new arraylist<>(arrays.aslist(new integer[]{1,2,3,4,5})); (listiterator<integer> = 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]
what have get: [1, 2, 3, 4, 5, 11, 12, 13, 14, 15] ?
my problem cannot solved creating list , using addall() after... explanation of problem poor, let me explain better:
arraylist<someclass> arr = new arraylist<>(); int condition = 12; // example contidition number (listiterator<someclass> = arr.listiterator(); i.hasnext();) { if (i.next().conditionnumber == condition) { // add final of list process after elements. } else { // process element. // change contidition condition = 4; // example, number change many times } } i can't create separated list because elements add final may enter in condition again
thanks
since you're using java 8, use stream api. concat 2 streams of original list, 1 maps each element adding 10 it.
list<integer> arr = arrays.aslist(1, 2, 3, 4, 5); list<integer> result = stream.concat(arr.stream(), arr.stream().map(i -> + 10)) .collect(collectors.tolist()); as updated question, don't see why can't create list update continuously. i'd in case.
here's solution update list iterating using index-based loop, don't forget cache size before starting iterate, process elements in list before processing.
arraylist<someclass> arr = new arraylist<>(); int condition = 12; // example contidition number final int prevsize = arr.size(); (int = 0; < prevsize; i++) { someclass element = arr.get(i); if (element.conditionnumber == condition) { //probably update or create new element here arr.add(somenewelement); } else { // process element. // change contidition condition = 4; // example, number change many times } } i can't create separated list because elements add final may enter in condition again
it seems me dangerous behavior, may add elements indefinitely list, know real problem facing. if can try avoid better, imo.
Comments
Post a Comment