[英]The best way to sort list by item name length
哪種方式最好,看速度和舒適度?
names.sort( (a,b) -> a.getName().length() - b.getName().length() );
Collections.sort(names, Comparator.comparing( s -> Celebrity.getName().length() ))
BiFunction<Celebrity,Celebrity,Integer> bifunc = (a,b) -> Integer.compare(a.getName().length(), b.getName().length());
Collections.sort( names, bifunc::apply );
一樣的。 看看Collections.sort
方法:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
所有3種方法都按相同的算法排序。
您應該盡可能多地編寫代碼。 除非確實需要,否則不要進行過早的微量優化。
我會用這一行:
names.sort(Comparator.comparingInt(celebrity -> celebrity.getName().length()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.