Wang Zijun
Wang Zijun

Reputation: 9

how to sort each line on the file in scala?

I want sorted list of the names, last name first, one per line. Names will be ordered by the number of characters in the first name in ascending order, shortest first. Within each group of names of each length, they will be ordered by the number of characters in the last name in ascending order, shortest first.

Example:

xxx xxxxx

xxx xxxxx

xxx xxxxxx

xxx xxxxxxx

xxxx xxx

xxxx xxxxx

xxxx xxxxxxx

i append the name to a list of list like this List(List(Samantha, Sanderfur), List(Kathlene, Lamonica), List(Dixie, Crooker), List(Domitila, Rutigliano))

and i want sort this list of list. Idk how should i sort this, or some other way to solve this problem.

Upvotes: 0

Views: 180

Answers (3)

Wang Zijun
Wang Zijun

Reputation: 9

Ty guys for help me. I use sortwith to sort list of list here is my code

val s=v.sortWith((x,a)=>if(x(0).length==a(0).length){
  x(1).length<a(1).length
}
else{
  x(0).length<a(0).length
})
var z=""
for(i<- s){
  z=i(0)+" "+i(1)
  println(z)
}

Upvotes: 0

Anupam Kumar
Anupam Kumar

Reputation: 173

try below code:

val names = List(("Jack","Wilson"),("Alex","Jao"),("Jack","Wildorsowman"),
    ("Jack","Wiliamson"),("Alex","Joan"),("Alex","J."))

println(names.sortBy( x => (x._1.length(),x._2.length())))

Result:

List((Alex,J.), (Alex,Jao), (Alex,Joan), (Jack,Wilson), (Jack,Wiliamson), (Jack,Wildorsowman))

UPDATED with suggestion from @GalNaor -

val names = `List(List("Jack","Wilson"),List("Alex","Jao"),List("Jack","Wildorsowman"),List("Jack","Wiliamson"),List("Alex","Joan"),List("Alex","J."))`

println(names.sortBy{ case List(x,y) => (x.length(),y.length())})

Result:

List(List(Alex, J.), List(Alex, Jao), List(Alex, Joan), List(Jack, Wilson), List(Jack, Wiliamson), List(Jack, Wildorsowman))

Upvotes: 2

Gal Naor
Gal Naor

Reputation: 2397

This is how I would do it:

val input = List(List("aa","bbb"), List("a", "bb"), List("aaaa", "b"), List("aa", "bb"))

val tupleInput = input.map{case List(a,b) => (a,b)} 
// List((aa,bbb), (a,bb), (aaaa,b), (aa,bb))

val sortedMapValues = tupleInput.groupBy(_._1).mapValues(_.sorted) 
// Map(a -> List((a,bb)), aaaa -> List((aaaa,b)), aa -> List((aa,bb), (aa,bbb)))

val sortedMapKeys = scala.collection.immutable.TreeMap(sortedMapValues.toArray:_*) 
// Map(a -> List((a,bb)), aa -> List((aa,bb), (aa,bbb)), aaaa -> List((aaaa,b)))

val result = sortedMapKeys.map{case (_, a) => a}

// result = List(List((a,bb)), List((aa,bb), (aa,bbb)), List((aaaa,b)))

You can play with it here

Another one-liner solution can be like this (here) - Thanks to @Anupam Kumar (a little adjustment need to be done to make his solution fit the input required):

val result = input.sortBy{case List(x,y) => (x.length(),y.length())}

Thanks @jwvh for the making it even shorter.

Upvotes: 2

Related Questions