Reputation: 357
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!
Upvotes: 3
Views: 4209
Reputation: 931
You can convert your array list to set.
Set<String> foo = new HashSet<String>(pinyinArrayList);
Upvotes: 3
Reputation: 31700
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
Upvotes: 6