Sort float / double list that are in String format using Comparator.comparing

I want to sort the list of float values ​​available in String format, 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 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()); 
+5
source share
1 answer

you can replace Room::getRate with r -> Float.parseFloat(r.getRate()) , and then it becomes this:

  sorted(Comparator.comparing( r -> Float.parseFloat(r.getRate), Comparator.naturalOrder()) 

OR

 Comparator.comparingDouble(r -> Double.parseDouble(r.getRate())) 
+8
source

Source: https://habr.com/ru/post/1272398/


All Articles