2
對於下面的代碼:Comparator.comparing()函數是如何工作的?
ForComparatorDemo object1 = new ForComparatorDemo("object-1",5);
ForComparatorDemo object2 = new ForComparatorDemo("object-2",4);
ForComparatorDemo object3 = new ForComparatorDemo("object-3",3);
ForComparatorDemo object4 = new ForComparatorDemo("object-4",4);
List<ForComparatorDemo> objectList = new ArrayList<>();
objectList.add(object1);
objectList.add(object2);
objectList.add(object3);
objectList.add(object4);
Comparator<ForComparatorDemo> comparer = Comparator.comparing(ForComparatorDemo::getAge);
objectList.sort(comparer);
objectList.forEach(object -> System.out.println(object.getName() + " " + object.getAge()));
我得到這個輸出(這是正確的):
對象-3 3
對象-2 4
對象-4 4
object-1 5
問題是怎麼回事那比較功能實際上工作? 挖掘到的文件後,我發現這個代碼Coamparator.comparing(..)功能:
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
你能解釋一下我這個功能是如何得到這兩個值(C1和C2),以及如何return語句的實際工作?
那麼我實際上是在尋找的是這個函數如何獲得參數c1和c2以及答案來自我在挖掘到文檔後發現的List接口 –
我已經添加了關於比較器使用的部分。 – arghtype