Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of floats/double which are in String format with Comparator.comparing

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());
like image 815
Abhishek Galoda Avatar asked Oct 06 '17 14:10

Abhishek Galoda


1 Answers

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()))
like image 128
Eugene Avatar answered Nov 04 '22 21:11

Eugene