Stream groupingBy by one field then merge all others

Viewed 5932

I have trouble with stream groupingby.

List<FAR> listFar = farList.stream().filter(f -> !f.getStatus().equals(ENUM.STATUS.DELETED))
            .collect(Collectors.toList());
List<HAUL> haulList = listFar.stream().map(f -> f.getHaul()).flatMap(f -> f.stream())
            .collect(Collectors.toList());

It groups by specie, it's all fine, but there are another attributes to HAUL.

Map<Specie, List<HAUL>> collect = haulList.stream().collect(Collectors.groupingBy(HAUL::getSpecie));

Attributes:

  1. haul.getFishCount(); (Integer)
  2. haul.getFishWeight(); (BigDecimal)

Is it possible to group by HAUL::getSpecie (by Specie), but also "merging" together those two extra fields, so I have total?

For example: I have 3 of HAUL elements where fish specie A has 50/30/10 kg in weight.

Can I group it by specie and have total weight?

3 Answers
Related