尝试在Kotlin中迭代哈希图

时间:2018-07-22 00:40:22

标签: loops dictionary kotlin hashmap

这是哈希图,当我尝试对其进行迭代并仅打印值时,例如,我从随机位置获得了值。为什么不显示0.92、0.91、0.90 ...

val map: HashMap<Int, Double> =
        hashMapOf(400 to 0.92, 383 to 0.91, 366 to 0.9, 351 to 0.89, 336 to 0.88, 322 to 0.87, 309 to 0.86, 296 to 0.85, 284 to 0.84,
                273 to 0.83, 262 to 0.82, 251 to 0.81, 240 to 0.8, 230 to 0.79, 220 to 0.78, 211 to 0.77, 202 to 0.76, 193 to 0.75,
                184 to 0.74, 175 to 0.73, 166 to 0.72, 158 to 0.71, 149 to 0.7, 141 to 0.69, 133 to 0.68, 125 to 0.67, 117 to 0.66,
                110 to 0.65, 102 to 0.64, 95 to 0.63, 87 to 0.62, 80 to 0.61, 72 to 0.6, 65 to 0.59, 57 to 0.58, 50 to 0.57, 43 to 0.56,
                36 to 0.55, 29 to 0.54, 21 to 0.53, 14 to 0.52, 7 to 0.51, 0 to 0.5, -7 to 0.49, -14 to 0.48, -21 to 0.47, -29 to 0.46,
                -36 to 0.45, -43 to 0.44, -50 to 0.43, -57 to 0.42, -65 to 0.41, -72 to 0.4, -80 to 0.39, -87 to 0.38, -95 to 0.37,
                -102 to 0.36, -110 to 0.35, -117 to 0.34, -125 to 0.33, -133 to 0.32, -141 to 0.31, -149 to 0.3, -158 to 0.29, -166 to 0.28,
                -175 to 0.27, -184 to 0.26, -193 to 0.25, -202 to 0.24, -211 to 0.23, -220 to 0.22, -230 to 0.21, -240 to 0.2, -251 to 0.19,
                -262 to 0.18, -273 to 0.17, -284 to 0.16, -296 to 0.15, -309 to 0.14, -322 to 0.13, -336 to 0.12, -351 to 0.11, -366 to 0.1,
                -383 to 0.09, -400 to 0.08)

    val iterator  = map.iterator()
    iterator.forEach{

        println(map.get(it.key))
    }

迭代后的结果

0.5 0.32 0.68 0.18 0.82 0.49 0.51 0.31 0.69 0.48 0.52 0.08 0.92 0.17 0.83 0.47 0.3 0.7 0.53 0.16 0.84 0.46 0.54 0.29 0.71 0.45 0.55 0.28 0.72 0.15 0.85 0.44 0.56 0.27 0.73 0.43 0.57 0.14 0.86 0.26 0.74 0.42 0.58 0.41 0.25 0.75 0.59 0.13 0.87 0.4 0.6 0.24 0.76 0.39 0.12 0.88 0.61 0.23 0.77 0.38 0.62 0.22 0.78 0.37 0.11 0.89 0.63 0.36 0.21 0.79 0.64 0.35 0.1 0.9 0.65 0.2 0.8 0.34 0.66 0.19 0.81 0.33 0.67 0.09 0.91

1 个答案:

答案 0 :(得分:0)

如果要保留地图中的插入顺序,则需要使用val map: Map<Int, Double> = linkedMapOf(...

.then()