1

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!

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.