Return sorted list in Java
•
Java
I'm writing this Code:
List<Bean> beans = service.findBeans(); Collections.sort(beans,new BeanComparator()); return beans;
It works perfectly What I'm looking for is a one line shortcut:
return somelibrary.Collections.sort(service.findBeans(),new BeanComparator());
or
return somelibrary.newList(service.findBeans(),new BeanComparator());
Note that it requires a variable list
Solution
This is a line:
List<Bean> beans = service.findBeans(); Collections.sort(beans,new BeanComparator()); return beans;
But more seriously, Java is not the right language And just because something is single doesn't mean it's better For example, I was initially surprised to find this:
return condition ? a : b;
Create a bytecode longer than
if( condition ) return a; else return b;
But that's how languages and compilers work
If you stick to your single line, guava's ordering can:
return Ordering.from( new BeanComparator() ).sortedCopy( service.findBeans() );
The returned list is modifiable, serializable, and has random access
In terms of efficiency, I think there is some waste in spending In addition, you now rely on third - party libraries You essentially use very powerful tools to accomplish a very simple task If you're using it, it's too much
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码