title: Group a Scala list by custom logic
body: <p>I have a custom logic to group a list of names by their first letter and I can achieve it by the following:</p>
  
  <pre><code>val names = List("Adam", "Barbara", "Bob", "Charlie", "Damien", "Elaine", "Florence", "Gwen")
  names.map{
    case x if x.startsWith("A") =&gt; (1, x)
    case x if x.startsWith("B") =&gt; (1, x)
    case x if x.startsWith("C") =&gt; (2, x)
    case x if x.startsWith("D") =&gt; (2, x)
    case x if x.startsWith("E") =&gt; (3, x)
    case x if x.startsWith("F") =&gt; (3, x)
    case default =&gt; (0, default)
  }.groupBy(_._1)
  </code></pre>
  
  <p>The logic may change. For example, next time I may want to group all names starting with A, F and G to group 1 or I may add all letters up to Z. A more advanced logic would be to take the first two letters and group names starting with Ad and Ba to group 1, in which case Adam and Barbara would be in the same group.</p>
  
  <p>I'd like to know if there is a more idiomatic approach, where I can write <code>startsWith</code> lesser number of times.</p>
  
  <p>From <a href="https://stackoverflow.com/questions/43414258/group-a-scala-list-by-custom-logic/43414630#43414630">Tanjin's answer</a>, I further refactored <code>groups</code> to:</p>
  
  <pre><code>val groups = List(
        (List("A", "B"),1),
        (List("C", "D"),2),
        (List("E", "F"),3)
      ).flatMap{ case (l,i) =&gt; l.map((_, i)) }
  </code></pre>