Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream how to unpack a object with quantity to list of single object

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?

like image 305
alessmar Avatar asked Jun 24 '20 07:06

alessmar


1 Answers

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());
}
like image 135
ernest_k Avatar answered Sep 28 '22 05:09

ernest_k