JHK
JHK

Reputation: 51

How to get an attribute of an object that is stored in array list of array lists?

I have an arrayList LAL that is filled with other arraylists via add function, like that:

for(int i=0;i<v_amountComponentOptions;i++){
    ArrayList AL=new ArrayList<CustomerOrder>();
    LAL.add(AL);
}

Then I add orders (orders have the attribute product and quantity) to this List of Array List, like that:

LAL.get(0).add(order);

When I try to plot the quantity as follows, I get an error. It says that there is no quantity value.

traceln(LAL.get(0).get(0).quantity);

However, when I write;

traceln(LAL.get(0).get(0).quantity);

Then, the output is :

root( product = 1, quantity = 63 )

My point is that I need to get the quantity value. Could anyone tell me how to do that? Thank you very much.

Upvotes: 0

Views: 71

Answers (1)

WJS
WJS

Reputation: 40034

One possiblity is to use a stream and put all the quantity values in a List. Assuming the quantities are Integers and the quantity value is accessible you could do something like this.

List<Integer> list = LAL.stream()
                 .flatMap(List::stream)
                 .map(a->a.quantity)
                 .collect(Collectors.toList());

And if you had getters, this would be even better.

List<Integer> list = LAL.stream()
                 .flatMap(List::stream)
                 .map(CustomerOrder::getQuantity)
                 .collect(Collectors.toList());

Upvotes: 1

Related Questions