[英]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 eg, 我想对以String格式提供的浮点值列表进行排序,例如,
"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. 如果我使用Comparator.comparing(Room :: getRate),列表将按字符串顺序排序,这将是不正确的。 So I wrote the code below where I convert String to float and then compare. 所以我编写了下面的代码,我将String转换为float然后进行比较。
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: 您可以将Room::getRate
r -> Float.parseFloat(r.getRate())
替换为r -> Float.parseFloat(r.getRate())
,然后它将变为:
sorted(Comparator.comparing(
r -> Float.parseFloat(r.getRate),
Comparator.naturalOrder())
OR 要么
Comparator.comparingDouble(r -> Double.parseDouble(r.getRate()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.