3

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!

2
  • To get back to the original question of why your code doesn't work - no idea, it prints the already contained statements just as expected for me. Commented Jun 13, 2017 at 4:23
  • Edited my question to explain why - oops! Commented Jun 13, 2017 at 9:57

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, will use this to clean my code! However, I realised what the problem was and edited my question to clarify.
3

You can convert your array list to set.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.