Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

collections - How do i filter and copy values to a list of objects based on another list in Kotlin

I am trying to filter a list of objects based on a certain condition from a second list and then update/copy certain values from the second list to the already filtered list.

I tried this:

val filteredList = firstObjectList.stream()
    .filter { first ->
        secondObjectList.stream()
            .anyMatch { second ->
               second.sharedId == first.shareId
            }
    }.toList()

filteredList.map { filtered ->
    secondObjectList.forEach { so ->
        if(filtered.shareId == so.shareId){
            val asset= Assets()
            asset.address = so.address
            asset.assetValue = so.assetValue
            filtered.asset = asset
    }
}

}

return filteredList

here are the objects:

Class firstObject(
val  shareId: Int, 
var asset : Asset? = null)

Class secondObject(
val shareId: Int,
var asset: Assets)

Class Assets(
val address: String,
val assetValue: Double)

This works but obviously not very efficient and Java based. How can I improve and write this in idiomatic kotlin? as i don’t seem to be able to chain operators correctly. Thanks in Advance.

question from:https://stackoverflow.com/questions/65836670/how-do-i-filter-and-copy-values-to-a-list-of-objects-based-on-another-list-in-ko

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
val map = secondObjectList.associateBy { it.shareId }
val filteredList = firstObjectList
    .filter { it.shareId in map }
    .onEach { fo ->
        fo.asset = map.getValue(fo.shareId).asset.let { Assets(it.address, it.assetValue) }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...