Kotlin Set collection traversal

code

It's a simple way to sort out the traversal

fun main(args: Array<String>) {

    //创建有序可变set
    val mutableSetOf = mutableSetOf<String>("g", "h", "p", "w", "w")
    //创建无序可变set ---类似java
    val hashSetOf = hashSetOf<String>("g", "h","p","w","w")//无序的
    /**
     * 遍历方式1:for-in 循环:
     * 有序和无序都适用
     */
    for ( i in mutableSetOf){
        print(i)
    }
    println()
     for(i in hashSetOf){
         print(i)
     }
    println()

    /**
     * 遍历方式2:forEach  ,因为set集合继承了Iteratable ,所以可以使用该接口的foreach方法
     * 有序和无序都适用
     */
     mutableSetOf.forEach { print(it)  }
    println()
    hashSetOf.forEach { print(it) }
    println()

    /**
     * 遍历方式2:通过索引来遍历有序set
     * 有序适用,无序的不适用
     * mutableSetOf.indices:返回有序集合的索引区间
     * mutableSetOf.elementAt(i):得到索引为i的值
     */
    for (i in mutableSetOf.indices){
        print(mutableSetOf.elementAt(i))
    }

}


result print

run result.png

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324728349&siteId=291194637