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;
}
Run Code Online (Sandbox Code Playgroud)
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());
}
Run Code Online (Sandbox Code Playgroud)