0

I have List that looks like this:

List

[{
type: "1"
price: 10.0
count: 2
},
type: "1"
price: 15.0
count: 3
},
type: "2"
price: 20.0
count: 2
},
type: "2"
price: 30.0
count: 3
}]

I need to group this such that I only have two types (in this case).

Output:

[{
type: "1"
price: 25.0
count: 5
},
type: "2"
price: 50.0
count: 5
}]

So, basically, the number of elements in the list will be equal to the number of unique types. And other values like price and count will be summed.

I tried using this -

report.stream().collect(Collectors.groupingBy(x -> x.getStuffe));

But, this gives a Map. I don't need a Map, I need a List.

How can I do this?

nirvair
  • 4,001
  • 10
  • 51
  • 85

2 Answers2

0

Try doing something like:

if (<types of list are equal>) {
    //add other attributes together
}
Raymo111
  • 514
  • 8
  • 24
0

why do you need streams? this is easy to do in a loop, hashmap aggregation and ultimately dumping values collection. All these iterations are essentially done under the hood of streams, so it's not slower, just more verbose.

HashMap map = new HashMap();
for(Item x: list){
  Item old = map.put(x.type, x);
  if(old!=null) {
    x.price += old.price;
    x.count += old.count;
  }
}
return new ArrayList(map.values());
user2023577
  • 1,752
  • 1
  • 12
  • 23