简体   繁体   中英

Scala Sort based on a number in the string

I have a file which has lines of the type:

A 2.3 B 5.6
A 5.4 B 3.5
A 5.6 B 3.4

I want to read the file and sort it based on the second column that is 2.3,5.4,5.6 and extend the sort to all the columns so the output should be:

A 5.6 B 3.4
A 5.4 B 3.5
A 2.3 B 5.6

I was thinking of reading the file as list and then doing a match to get second column and then sorting. Is there a better way?

You have the right idea, but be aware that there is a command line utility to do this for you:

$ sort -k2 -n -r
A 2.3 B 5.6
A 5.4 B 3.5
A 5.6 B 3.4
^D
A 5.6 B 3.4
A 5.4 B 3.5
A 2.3 B 5.6

If you really wanted to do it in scala, you would need to read it into memory, and then sortWith a comparator that looks at the second field in each row.

You probably want something like

val src = scala.io.Source.fromFile("filename")
val lines = src.getLines.toSeq.sortBy(line => -line.split(' ').apply(1).toDouble)
src.close

(the negative is to sort largest-first; default is smallest-first).

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