I would like to learn Kotlin and try to transfer multiple objects that each manage two ints to one list that manages a hashmap of two ints.
This is the new object:
public class HashObject(val maps: MutableList<HashMap<Int, Int>>){
...
}
This is the old object:
public class OldObject(
val a: Int,
val b: Int
)
I have a list of the old objects:
val oldObjects: List<OldObject> = ...
And i am trying to transfer it like this:
val hashObjects = mutableListOf<HashMap<Int, Int>>()
for(obj in oldObjects){
hashObjects.add(hashMapOf(obj.a to obj.b))
val result = HashObject(maps = hashObjects)
But I get the following error:
Type mismatch.
Required: kotlin.collections.HashMap<Int, Int> /* = java.util.HashMap<Int, Int> */
Found: MutableList<java.util.HashMap<Int, Int>>
How can I solve this problem?
CodePudding user response:
Another way to do what you're asking is
val result = oldObjects.map { oldObj -> hashMapOf(oldObj.a to oldObj.b) }
.toMutableList()
CodePudding user response:
The question seems a bit confused, but I suspect that what's really needed is a single map from Int to Int. One of the simplest (and most efficient) ways to get that is:
val result = oldObjects.associate{ it.a to it.b }
That gives a Map<Int, Int>
, with one entry for each of the original OldObjects. (With the caveat that if multiple OldObjects have the same key, only the last will be included in the result. If you need to preserve them all in that case, then a map isn't the right structure.)
(If you need the result to be mutable, you can then call toMutableMap()
on it — but in general it's simpler and safer to stick to immutable objects where possible.)