简体   繁体   中英

Copy All the elements/object of one list N times to new list. Using java 8 stream

Copy all the elements of one list N times in a new list.

I have list of Fruits which i want to iterate to N times and add all the value to new list but the in the list we have less then my iteration so i want to add Empty fruits with incremental id. how to do using java 8 and stream programming. I have total 7 fruits in my current list but i want to looped in 10 time copied all data to new list and if data is not available in the index then i want to add empty object with incremental ids. I tried but not getting expected result.

@Data
@AllArgsConstructor 
public class Fruit {
   int id;
   String type;
}

List<Fruit> fruits = new ArrayList<>();
    fruits.add(new Fruit(1, "mango"));
    fruits.add(new Fruit(2, "grapes"));
    fruits.add(new Fruit(3, "apple"));
    fruits.add(new Fruit(4, "banana"));
    fruits.add(new Fruit(5, "papaya"));
    fruits.add(new Fruit(6, "jack fruit"));
    fruits.add(new Fruit(7, "dragon fruit"));
List<Fruit> newFruits = new ArrayList<>();

    fruits.stream().map(value -> {
        IntStream.rangeClosed(1, 10).forEach(index -> {
            if (value.equals(null))
                newFruits.add(new Fruit(index, ""));
            else
                newFruits.add(value);
        });
        return null;
    });

Expected OP: for newFruits

newFruits :
[Fruit(id=1, type=mango), 
 Fruit(id=2, type=grapes), 
 Fruit(id=3, type=apple), 
 Fruit(id=4, type=banana), 
 Fruit(id=5, type=papaya), 
 Fruit(id=6, type=jack fruit), 
 Fruit(id=7, type=dragon fruit),
 Fruit(id=8, type="").
 Fruit(id=9, type=")
 Fruit(id=10, type="")]

Streams might not be the right tool for this task. Why not just add all elments from original list to new list and calculate how many new entries to add after finding the largest id? Something like:

List<Fruit> newFruits =  new ArrayList<>();
newFruits.addAll(fruits);

int N = 10;
int toAdd = N - fruits.size();
int maxId = fruits.stream().mapToInt(Fruit::getId).max().orElse(0);

IntStream.rangeClosed(1,toAdd).forEach(i -> newFruits.add(new Fruit(maxId + i, "")));

Or take a look at @Holger's comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM