I want to sort a list of float values which are available in String format for e.g.,
"rate": "429.0",
"rate": "129.0",
"rate": "1129.0",...
If I use Comparator.comparing(Room::getRate) the list will be sorted in String order which will be incorrect. So I wrote the code below where I convert String to float and then compare.
Below code works fine for me, but it looks so ugly, is there a better alternative?
stream().sorted(Comparator.comparing(Room::getRate,
(s1, s2) -> (Float.parseFloat(s1) > Float.parseFloat(s2) ? 1 :-1)))
.collect(Collectors.toList());
you can replace Room::getRate
to r -> Float.parseFloat(r.getRate())
and then it would become:
sorted(Comparator.comparing(
r -> Float.parseFloat(r.getRate),
Comparator.naturalOrder())
OR
Comparator.comparingDouble(r -> Double.parseDouble(r.getRate()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With