HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Finding the longest word from a list of words

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fromthewordswordfindinglistlongest

Problem

I have a list of words (with repetitions), and I intend to find out the longest words amongst them, along with their length. My question is to know if my implementation is too verbose, is using too many operators/functions and if so, what are the better, more idiomatic, readable alternatives.

Given the list below, the expected output is

Max length=3, words are "mnp","pqr","jkl","abc","xyz"


val line = List("a","ab","abc","xyz","mnp","ac","d","b","ab","bc","bd","be","bf","b","abc","abc","pqr","mnp","jkl","a","b")

    val lengthAndTheWords = line.map(x => (x.length,x)).groupBy(x => x._1).mapValues(x => x.toSet)
    val longest = lengthAndTheWords.toSeq.sortBy(key => -key._1).head

    println("Max length =" + 
            longest._1 +
            ", words are" + 
            longest._2.map(nextEntry => nextEntry._2).mkString(","))


(With an Ideone running the code)

I consider myself an intermediate level Scala programmer; so, I am looking for all tips to improve my skills in Scala.

Solution

Whenever I only use the extracted value once in a simple group / map / sortBy monadic operations I use the _ placeholders. I think it makes the code a little more compact and readable, especially if it was just a placeholder value like x

.groupBy(x => x._1) becomes .groupBy(_._1)

.mapValues(x => x.toSet) becomes .mapValues(_.toSet) or even mapValues toSet if you like infix

It's not a universal rule by any means, sometimes you really need a meaningful name so that another coder could make sense of it.

Edit
Also you can go straight to the group by and remove redundant counts

val oneLiner = line.groupBy(_.length).mapValues(_.toSet).maxBy(_._1)

//> oneLiner  : (Int, scala.collection.immutable.Set[String]) = (3,Set(abc, pqr, mnp, jkl, xyz))

Code Snippets

val oneLiner = line.groupBy(_.length).mapValues(_.toSet).maxBy(_._1)

//> oneLiner  : (Int, scala.collection.immutable.Set[String]) = (3,Set(abc, pqr, mnp, jkl, xyz))

Context

StackExchange Code Review Q#53972, answer score: 2

Revisions (0)

No revisions yet.