kotlinip-addresskotlin-higher-order-functions

Using Kotlin HOFs to split, transform, and join elements from String list


Goal:

Given a list of String representing IP addresses

Example

        input:      8.219.27.102
        output:     008219027102
    

I've got code to do this imperatively, but am attempting to solve it using just Kotlin higher-order list functions.

 val ipList = arrayListOf<String>(
        "8.219.27.102","13.111.16.143","104.168.41.0","104.168.41.84","104.206.192.0","104.223.153.0",
        "168.203.37.240","192.3.195.0","198.255.103.0"
    )

// fun to transfrom octets 
//
fun padStringWithZeros(s: String) : String {
    return when (s.length) {
        1 -> "00$s"
        2 -> "0$s"
        else -> {
            s
        }
    }
}

Using map to split on '.' I get the 4 octets separated by ', '

val ipListXFormed =    ipList
  .map { it.split(".").toString() }
        
[8, 219, 27, 102]
[13, 111, 16, 143]
...

Adding a flatmap split on "," gets me the individual pieces

  val ipListXFormed =    ipList
        .map { it.split(".").toString() }.flatMap { it.split(",") }

[8
 219
 27
 102]
[13
 111
 16
 143]
...
 

But, if I try to use map to transform these pieces, it seems to be including the brackets as chars in the elements, which throws off the element size.

I'm a bit stuck here...can this be done simply with HOFs or would imperative style be more appropriate?


Solution

  • split already gives you a List<String>. But for some reason you call toString on it and tries to parse the string you got back into a List.

    Don't do that - just use what you get from split directly. Join the split octets again with joinToString, and use padStart to add the zeroes.

    ipList.map { ip ->
        ip.split('.')
            .joinToString(separator = "") {
                it.padStart(3, '0')
            }
    }