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:
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:
Creates a longer bytecode than
But that’s just how the language and compiler are.
If you insist on your one-liner, Guava‘s
Orderingcan do it: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.