Returned sorted list in Java

I am coding something like this:

List<Bean> beans = service.findBeans();
Collections.sort(beans, new BeanComparator());
return beans;

It works great. I am looking for a shortcut to do this with only one line:

return somelibrary.Collections.sort(service.findBeans(), new BeanComparator());

Or:

return somelibrary.newList(service.findBeans(), new BeanComparator());

Please note that this requires a mutable list.

+3
source share
6 answers

This is one line:

List<Bean> beans = service.findBeans(); Collections.sort(beans, new BeanComparator()); return beans;

But more seriously, Java is not exactly the right language for single-line. In addition, just because something is single-line does not mean that it is better. For example, I was initially surprised to find that this:

return condition ? a : b;

Generates longer bytecode than

if( condition )
    return a;
else
    return b;

But it is both a language and a compiler.

If you insist on your one-liner, Guava Ordering can do this:

return Ordering.from( new BeanComparator() ).sortedCopy( service.findBeans() );

The returned list is modified, serialized and has random access.

- , . . . , , .

+9

, . .

public static <T> List<T> sort(List<T> list, Comparator<? super T> compare) {
    Collections.sort(list, compare);
    return list;
}
+4

apache CollectionUtils .

CollectionUtils.collate(service.findBeans().iterator(),Collections.EMPTY_LIST.iterator(),new beanComparator())

CollectionUtils , ...

- - LOGGING. , . - , , , .

, ( ) ( / nullsafe) ( , isDebugOn().

- , JOOQ, .

+2

, , :

return new ArrayList<Bean>(new TreeSet<Bean>(service.findBeans()));
+1

, . "Collections.sort(..)" , , :

List<Bean> beans = service.findBeans();
List<Bean> sortedBeans = new ArrayList<Bean>(beans);
Collections.sort(sortedBeans, new BeanComparator());
return sortedBeans;

, , , , . , , , ?

.

"Collections.sort(..)" , :

public void doSomethingWithBeansInOrder(List<Bean> beans) {
    Collection<Bean> sortedBeans = new ArrayList<Bean>(beans);
    Collections.sort(sortedBeans, ...comparator...;

    for (Bean bean : sortedBeans) {
        .. do something
    }
}

"sortedBeans" .

"(Collections.sort(..)" ( - ), , :

public void doSomethingWithBeansInOrder(List<Bean> beans) {
    for (Bean bean : Collections.sort(beans, ...comparator...) {
        .. do something
    }
}

Guava Ordering , .

+1

Java 8 sort() List. , :

List<Integer> integerList = Arrays.asList(3, 2, 1);
integerList.sort(Comparator.naturalOrder());
return integerList;

naturalOrder(), , , Comparable, . .

, , , :

integerList.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());

, , .

+1

All Articles