How does Scala's groupBy identity work?

后端 未结 6 1044
天涯浪人
天涯浪人 2021-02-01 05:56

I was browsing around and found a question about grouping a String by it\'s characters, such as this:

The input:

\"aaabbbccccdd\"
         


        
6条回答
  •  离开以前
    2021-02-01 06:26

    First, let's see what happens when you iterate over a String:

    scala> "asdf".toList
    res1: List[Char] = List(a, s, d, f)
    

    Next, consider that sometimes we want to group elements on the basis of some specific attribute of an object.

    For instance, we might group a list of strings by length as in...

    List("aa", "bbb", "bb", "bbb").groupBy(_.length)
    

    What if you just wanted to group each item by the item itself. You could pass in the identity function like this:

    List("aa", "bbb", "bb", "bbb").groupBy(identity)
    

    You could do something silly like this, but it would be silly:

    List("aa", "bbb", "bb", "bbb").groupBy(_.toString)
    

提交回复
热议问题