How does Scala's groupBy identity work?

后端 未结 6 1045
天涯浪人
天涯浪人 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:29

    This is your expression:

    val list = str.groupBy(identity).toList.sortBy(_._1).map(_._2)
    

    Let's go item by function by function. The first one is groupBy, which will partition your String using the list of keys passed by the discriminator function, which in your case is identity. The discriminator function will be applied to each character in the screen and all characters that return the same result will be grouped together. If we want to separate the letter a from the rest we could use x => x == 'a' as our discriminator function. That would group your string chars into the return of this function (true or false) in map:

     Map(false -> bbbccccdd, true -> aaa)
    

    By using identity, which is a "nice" way to say x => x, we get a map where each character gets separated in map, in your case:

    Map(c -> cccc, a -> aaa, d -> dd, b -> bbb)
    

    Then we convert the map to a list of tuples (char,String) with toList.

    Order it by char with sortBy and just keep the String with the map getting your final result.

提交回复
热议问题