I am coding something like this:
List<Bean> beans = service.findBeans();
Collections.sort(beans, new BeanComparator());
return beans;
It works perfectly. What I am looking for is a shortcut to do this with just one line:
return somelibrary.Collections.sort(service.findBeans(), new BeanComparator());
Or:
return somelibrary.newList(service.findBeans(), new BeanComparator());
Note that it is required a mutable list.
This is one line:
List<Bean> beans = service.findBeans(); Collections.sort(beans, new BeanComparator()); return beans;
But more seriously, Java isn't really the right language for one-liners. Also, just because something is a one-liner doesn't mean that it is any better. For example, I was initially surprised to discover that this:
return condition ? a : b;
Creates a longer bytecode than
if( condition )
return a;
else
return b;
But that's just how the language and compiler are.
If you insist on your one-liner, Guava's Ordering
can do it:
return Ordering.from( new BeanComparator() ).sortedCopy( service.findBeans() );
The returned list is modifiable, serializable, and has random access.
Efficiency-wise I think there's a bit of a waste in terms of overhead. And also you're now dependent on a 3rd-party library. You'd be essentially using very powerful tools for a very simple task. It's overkill if this is all you're using it for.
I believe the following function will yield the results you want. Just put it in the class of your choice.
public static <T> List<T> sort(List<T> list, Comparator<? super T> compare) {
Collections.sort(list, compare);
return list;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With