简体   繁体   English

Kotlin:改变类型MutableList <java.util.hashmap<int, int> > 至 kotlin.collections.HashMap <int, int></int,></java.util.hashmap<int,>

[英]Kotlin: change the type MutableList<java.util.HashMap<Int, Int>> to kotlin.collections.HashMap<Int, Int>

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.我想学习 Kotlin 并尝试将每个管理两个整数的多个对象转移到一个管理两个整数的 hashmap 的列表中。
This is the new object:这是新的 object:

public class HashObject(val maps: MutableList<HashMap<Int, Int>>){  
    ...  
}   

This is the old object:这是旧的 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?我怎么解决这个问题?

Another way to do what you're asking is做你要求的另一种方法是

val result = oldObjects.map { oldObj -> hashMapOf(oldObj.a to oldObj.b) }
    .toMutableList()

The question seems a bit confused, but I suspect that what's really needed is a single map from Int to Int.这个问题似乎有点混乱,但我怀疑真正需要的是从 Int 到 Int 的单个 map。 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.这给出了一个Map<Int, Int> ,每个原始 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.) (需要注意的是,如果多个 OldObjects 具有相同的键,则只有最后一个会包含在结果中。如果您需要在这种情况下保留它们,那么 map 不是正确的结构。)

(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.) (如果您需要结果是可变的,则可以对其调用toMutableMap() — 但一般来说,尽可能坚持不可变对象更简单、更安全。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM