UIB
UIB

Reputation: 113

Group a list by child elements list value in kotlin

I have 2 data classes

data class Channel (
        var ID : Int = 0,
        var ParametersList: List<Parameters>? = null
)

data class Parameters (
        var ParamKey : String = "",
        var ParamValue: String = ""
)

I have a list made out of Channel class

var channelList = mutableListOf<Channel>(
        Channel(0, mutableListOf<Parameters>(Parameters("SensorGroup","ABCD"),Parameters("Mode","1"))),
        Channel(1, mutableListOf<Parameters>(Parameters("SensorGroup","ABC"),Parameters("Mode","1"))),
        Channel(2, mutableListOf<Parameters>(Parameters("SensorGroup","ABCD"),Parameters("Mode","1")))
)

I need to group channels where ParamKey is "Sensor Group" and the ParamValues are the same

final result should be like

0=[Channel(ID=0, ParametersList=[Parameters(ParamKey=SensorGroup, ParamValue=ABCD), Parameters(ParamKey=Mode, ParamValue=1)]), Channel(ID=0, ParametersList=[Parameters(ParamKey=SensorGroup, ParamValue=ABCD), Parameters(ParamKey=Mode, ParamValue=1)])]

1=[Channel(ID=1, ParametersList=[Parameters(ParamKey=SensorGroup, ParamValue=ABC), Parameters(ParamKey=Mode, ParamValue=1)])]

I tried nested group by and filter couldnt achieve any meaning full result

Upvotes: 0

Views: 1362

Answers (2)

Tenfour04
Tenfour04

Reputation: 93551

You can use groupBy. Select the keys by first finding the Parameters with the appropriate ParamKey. Since these are nullable, the lambda might return null, so it would group all the invalid items together.

The result is a Map<String, Channel>, where the map keys are the unique ParamValue values. If you don't need the map, you can just get its values property.

val result = 
  channelList.groupBy { channel -> channel.ParametersList?.firstOrNull { it.ParamKey == "SensorGroup" }?.ParamValue }

By the way, Kotlin convention is to use lowercase first letters for property and variable names (so they are easily distinguished from class names and objects).

Upvotes: 2

Naor Tedgi
Naor Tedgi

Reputation: 5699

fun groupByParamKey(key: String) {
    val group = channelList.groupBy { it ->
        it.ParametersList?.first { it.ParamKey == key }?.ParamValue

    }
    print(group)
}

fun main(args: Array<String>) {
    groupByParamKey("SensorGroup")
}

Upvotes: 1

Related Questions