Sorry for not clearly the title, i'm still new to this and even English.
Collections.sort(aList, (s1, s2) -> Float.compare(s1.getAFloat(), s2.getAFloat()));
As above, can I use method references? if s1 and s2 are Floats and they don't use get-a-float method then things become easier:
Collections.sort(aList,Float::compare);
But with s1.getAFloat() I don't know how to use method reference or even possible to use it, thanks for answer!
-
1You can visit tutorials of how method reference works. java8tips.readthedocs.io/en/latest/…sanit– sanit2018年01月14日 06:27:17 +00:00Commented Jan 14, 2018 at 6:27
2 Answers 2
You can use
Collections.sort(aList, Comparator.comparing(ItemType::getAFloat));
And if the retrieved type aren't sortable already, you can give an additional comparator to comparing.
Comments
No you can't. Look into the following code.
List<Float> aList = Arrays.asList(5.2f, 9.7f);
Collections.sort(aList, (s1, s2) -> Float.compare(s1, s2));
Collections.sort(aList, Float::compare);
If your list elements were directly of Float type then you would have used method-reference.
If elements are not of Float type then you can do like this.
List<String> aList2 = Arrays.asList("5.2f", "9.7f");
aList2.stream().map(Float::valueOf).sorted(Float::compare)
.collect(Collectors.toList());