Created
October 12, 2020 12:59
-
-
Save crakaC/30ad422ecd92e096ede61d3fb227d8db to your computer and use it in GitHub Desktop.
KotlinのMapで特定のキーの範囲でループして場合によっては要素を削除するとき
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val map = mutableMapOf<Int, Int>().toSortedMap() | |
//https://docs.oracle.com/javase/jp/8/docs/api/java/util/TreeMap.html#subMap-K-K- | |
val iterator = map.subMap(l, r).iterator() | |
while(iterator.hasNext()){ | |
val it = iterator.next() | |
//do something | |
iterator.remove() | |
} |
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/TreeMap.java
subMap()で取得できるMapが元のmapの参照を持っているのでいい感じに動作しているっぽい
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
map.subMap()から取得したIteratorを操作して元のmapの要素が消えるのは直感的に気持ち悪さを感じるが、こうしないと
java.util.ConcurrentModificationException
で実行時に落ちる。