Using streams to find the highest unique values

Viewed 299

Let's say I have this simple Car object:

class Car {
  String id;
  String model;
  Integer price;  
}

Now I have a list of cars which might look like so:

{ Car(1, Commodore, 55000), Car(2, F150, 120000), Car(3, F150, 130000),
  Car(4, Camry, 50000), Car(5,Commodore,50000)}

I would like to filter any duplicate models out of the List, ensuring that I'm only keeping in the most expensive priced car of each duplicate, e.g:

{ Car(1, Commodore, 55000), Car(3, F150, 130000), Car(4, Camry, 50000) }

I believe that I can do this using the Streams API, but I'm just struggling to chain the right calls together.

In my head, I would imagine the pseudocode would be something like:

  • Collect all the cars, group by model
  • Use Collectors.maxBy() on each individual model's List to get the priciest
  • Amalgamate the resulting one-item lists into a global car list again

Trying to stitch that together got a bit messy though - any ideas?

2 Answers
Related