Reputation: 5231
Is it possible with Java stream API to duplicate items a few times?
For instance let's say we have a list of orders where each order has a product code and quantity. I want to get a list of product codes which contains n copies of the given code where n is the quantity.
When I got 2 orders ("product1" : 3x, "product2": 2x)
I want in result a list like this: ("product1", "product1", "product1", "product2", "product2")
Is there a pretty way to do that with streams without the old for
cycle?
Code looks like this:
@Data
public class OrderRow {
private String productCode;
private int quantity;
}
Upvotes: 2
Views: 554
Reputation: 11042
You need to use Stream.flatMap()
and create a new stream with the items for each row:
List<String> result = orderRows.stream()
.flatMap(row -> Stream.generate(row::getProductCode).limit(row.getQuantity()))
.collect(Collectors.toList());
You also can use this:
List<String> result = orderRows.stream()
.flatMap(row -> IntStream.range(0, row.getQuantity()).mapToObj(i -> row.getProductCode()))
.collect(Collectors.toList());
Upvotes: 0
Reputation: 31878
You can use flatMap
with Collections.nCopies
as :
public static List<String> products(List<OrderRow> orderRows) {
return orderRows.stream()
.flatMap(o -> Collections.nCopies(o.quantity, o.productCode).stream())
.collect(Collectors.toList());
}
Upvotes: 6