I have a list of "Item" objects list like:
public class Item {
private String name;
private int qty;
public Item() { }
public Item(String name, int qty) {
this.name = name;
this.qty = qty;
}
public List<Item> unpack() {
List<Item> items = new ArrayList<>();
items.add(new Item("foo", 2));
items.add(new Item("bar", 3));
items.add(new Item("baz", 1));
List<Item> unpackedItems = unpack(items);
System.out.println(unpackedItems.size()); // it should be == 6
return unpackedItems;
}
private List<Item> unpack(List<Item> items) {
// ..
}
}
Is there a way to "unpack" those object using streams to have a list of items eventually repeated if qty is greater than 1 so at the end I'll have objects with qty equals to 1?
You can flatten a nested stream based on qty
(this basically creates a qty
-sized int stream that is then mapped to a new Item
with qty = 1
per element, reusing the name):
private List<Item> unpack(List<Item> items) {
return items.stream()
.flatMap(item -> IntStream.range(0, item.qty)
.mapToObj(i -> new Item(item.name, 1)))
.collect(Collectors.toList());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With