Hoàng Vinh Quang
Hoàng Vinh Quang

Reputation: 19

method reference for instance method from static method

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!

Upvotes: 1

Views: 63

Answers (2)

daniu
daniu

Reputation: 14999

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.

Upvotes: 1

sanit
sanit

Reputation: 1764

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

Upvotes: 0

Related Questions