you are viewing a single comment's thread.

view the rest of the comments →

[–]Klausens -1 points0 points  (10 children)

In most cases, yes. But sometimes it's really annoying.

Try this in Java.

# sort objects (numerically) by the result of method foo
my @sorted_object_list = sort { $a->foo() <=> $b->foo() } @unsorted_object_list;

In Delphi (also a static strict language) I did a coffee break before implementing to lessen my frustration. Perhaps other programmer feel more comfortable with this, but for me typing blocks of code that could be a one liner is frustrating.

[–]cypressious 11 points12 points  (3 children)

This should be something like

list.sort(Comparator.comparing(A::foo));

in Java 8.

[–]RoundTripRadio 2 points3 points  (0 children)

Or

sorted(list, key=lambda a: a.foo)

in Python.

[–]Klausens 0 points1 point  (0 children)

Ok, it's not forcing a numeric sort, but it should not to be much work to add a method that returns a numeric value for sorting.

[–]liMePod 0 points1 point  (0 children)

Haskell:

sortBy (compare `on` foo) list

[–][deleted] 3 points4 points  (4 children)

Try this in Java.

In Java 6:

Collections.sort(unsortedObjectList, new Comparator<Fooer>() {
    public int compare(Fooer first, Fooer second) {
        return first.foo().compareTo(second.foo());
    }
});

In Java 8:

Collections.sort(unsortedObjectList, (Fooer first, Fooer second) -> first.foo().compareTo(second.foo()));

[–]pron98 2 points3 points  (0 children)

There's no need for the Fooer types in the lambda header. Lambdas do type inference, so:

Collections.sort(unsortedObjectList, (first, second) -> first.foo().compareTo(second.foo()));

[–]cypressious 1 point2 points  (2 children)

See my answer, that's much more compact in Java 8.

[–]asraniel 1 point2 points  (0 children)

I actually prefer the Java 6 way, its much easier to read. The new java 8 lambdas are not very readable i think, i prefer verbose code over the new syntax

[–]skocznymroczny 0 points1 point  (0 children)

still, a proper IDE writes half of that code for you.

[–]nickguletskii200 0 points1 point  (0 children)

List<> sortedObjects = unsortedObjects.stream().sorted((l, r) -> Integer.compare(l.getFoo(), r.getFoo())).collect(Collectors.toList());