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!

vektor
2,9648 gold badges46 silver badges74 bronze badges
asked Jan 14, 2018 at 6:11
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.

answered Jan 14, 2018 at 6:50
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());
answered Jan 14, 2018 at 6:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.