简体   繁体   English

将一个列表的所有元素/对象 N 次复制到新列表。 使用 java 8 stream

[英]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.将一个列表的所有元素复制 N 次到一个新列表中。

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.我有 Fruits 列表,我想迭代 N 次并将所有值添加到新列表,但在列表中我们的迭代次数少于我的迭代次数,所以我想添加具有增量 ID 的 Empty fruits。 how to do using java 8 and stream programming.如何使用 java 8 和 stream 编程。 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.我当前列表中共有 7 个水果,但我想循环 10 次将所有数据复制到新列表,如果索引中没有数据,那么我想添加带有增量 ID 的空 object。 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预期的 OP:对于 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. Streams 可能不是完成此任务的正确工具。 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?为什么不直接将原始列表中的所有元素添加到新列表中,并在找到最大 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.或者看看@Holger 的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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