Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return sorted list in Java

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.

like image 515
falsarella Avatar asked Nov 30 '22 14:11

falsarella


2 Answers

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.

like image 134
trutheality Avatar answered Dec 17 '22 18:12

trutheality


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;
}
like image 36
Kodi Avatar answered Dec 17 '22 16:12

Kodi