简体   繁体   中英

Creating an ArrayList of unique items in an ArrayList

I would like my code to create an ArrayList (uniquePinyinArrayList) of unique items from an existing ArrayList (pinyinArrayList) which contains duplicates.

The "println" commands do not execute (I think they should do when a duplicate is from the pinyinArrayList is found in uniquePinyinArrayList)

fun uniquePinyinArray(pinyinArrayList: ArrayList<String>) {
    val uniquePinyinArrayList = ArrayList<String>()
    for(currentPinyin in pinyinArrayList){
        if (currentPinyin in uniquePinyinArrayList){
            // do nothing
            println("already contained"+currentPinyin)
            println("uniquePinyin"+uniquePinyinArrayList)
        }
        else {
            uniquePinyinArrayList.add(currentPinyin)
        }
    }
}

I have also tried

if (uniquePinyinArrayList.contains(currentPinyin)){

, though this also didn't work.

Edit: This method actually gets run for each word from my list of source-words, and hence multiple ArrayLists are created. To fix this, I made a single ArrayList object for uniquePinyin outside of this loop. Things work as expected now!

Check out the distinct() function, it will do all of this for you!

fun main(args: Array<String>) {
    val listOfThings = listOf("A", "B", "C", "A", "B", "C")
    val distinctThings = listOfThings.distinct()

    println(listOfThings)  // [A, B, C, A, B, C]
    println(distinctThings)  // [A, B, C]
}

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/distinct.html

您可以将阵列列表转换为set。

 Set<String> foo = new HashSet<String>(pinyinArrayList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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