yo1122
yo1122

Reputation: 321

how to sort a list according to a specific field in one line? (in java)

Given a list (ArrayList), containing items from a specific class (also given, called "Point"), how can I sort the list according to a specific field(of type int) in Point class (only the x-dimension)?

I tried this answer, and I know the function: Collections.sort(list_name, new comperator_name) usually works - but I cannot change the class point or change anything other than one line in the main function.

Two solutions would be appreciated: one for a point class without "compare" or "compareTo" functions, and one with a "compare" function.

Edit: for some reason someone suggested this as a duplicate - and I saw it before, but specifically asked for a solution that does not need to implement a comperator.

Upvotes: 1

Views: 2558

Answers (2)

Leandro Borges Ferreira
Leandro Borges Ferreira

Reputation: 12782

Now Java 8 List has

List.sort(Comparator<? super E> c). 

And the Comparator has:

comparing(Function<? super T,? extends U> keyExtractor)

So you can do you can use use

List.sort(Comparator.comparing(Point::someField))

Java 8 had many updates in the Collections package, so now you have many new methods and you can use to make your code thiner... Like sort a list with just one line.

Have fun!

Read here: https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

And here: https://docs.oracle.com/javase/8/docs/api/java/util/List.html

For more info about Comparator an List in Java 8.

Upvotes: 1

dghtr
dghtr

Reputation: 581

List.sort(Comparator<? super E> c). 

add the comparator then

comparing(Function<? super T,? extends U> keyExtractor)

and then finally use

List.sort(Comparator.comparing(Point::someField))

Upvotes: 0

Related Questions