96. Using records in streams
Consider the MelonRecord
that we have used before:
public record MelonRecord(String type, float weight) {}
And a list of melons as follows:
List<MelonRecord> melons = Arrays.asList(
new MelonRecord("Crenshaw", 1200),
new MelonRecord("Gac", 3000),
new MelonRecord("Hemi", 2600),
...
);
Our goal is to iterate this list of melons and extract the total weight and the list of weights. This data can be carried by a regular Java class or by another record as follows:
public record WeightsAndTotalRecord(
double totalWeight, List<Float> weights) {}
Populating this record with data can be done in several ways, but if we prefer the Stream API then most probably we will go for the Collectors.teeing()
collector. We won’t go into too much detail here, but we’ll quickly show that it is useful for merging the results of two downstream collectors. (If you’re interested,...