I have a list of locations returned by Google places API and decided to find a Place with a lowest price.
Here is how I implemented it with Java 8:
BigDecimal lowestPrice = places.stream()
.collect(Collectors.groupingBy(Place::getPrice, Collectors.counting()))
.entrySet().stream().min(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(BigDecimal.ZERO);
It returns me the lowest price but it'll be great to get a name of the Place as well (it has a name
attribute).
How can I also return a name
of the place with a lowest price?
Firstly, it's really unclear what you want as at first, you seem to say that
I have a list of locations returned by Google places API and decided to find a Place with a lowest price.
then at the bottom of your description, you say that:
It returns me the lowest price but it'll be great to get a name of the Place as well (it has a name attribute).
as if the latter seems to be what you want?
Nevertheless, here are both solutions:
if you want to find the min value by the count after grouping for whatever reason that may be... then you could do something along the lines of:
places.stream()
.collect(Collectors.groupingBy(Place::getPrice))
.entrySet().stream()
.min(Comparator.comparingInt((Map.Entry<Integer, List<Place>> e) -> e.getValue().size()))
.map(e -> new SimpleEntry<>(e.getKey(), e.get(0)));
note that above i've used Integer
as the entry key, feel free to change this to the appropriate type if it's not an Integer
.
Otherwise, if you're simply after the object with the lowest price then you can do:
places.stream().min(Comparator.comparingInt(Place::getPrice));
or:
Collections.min(places, Comparator.comparingInt(Place::getPrice));
There's no need for grouping and all the stuff going on.