简体   繁体   中英

The best way to sort list by item name length

Which of this ways is the best, looking at speed and comfort?

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

It's the same. look at Collections.sort method :

public static <T> void sort(List<T> list, Comparator<? super T> c) {
   list.sort(c);
}

All 3 approaches are sorted by the same algorithm.

You should write code as much as readable as possible. Don't do premature micro-optimalizations unless really needed.

I would use this one line:

names.sort(Comparator.comparingInt(celebrity -> celebrity.getName().length()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM