简体   繁体   中英

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.

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM