
It preserves the iteration order of the elements as it uses LinkedHashSet implementation of a MutableSet. Return type of toMutableSet() is a MutableSet. This function will create a new MutableSet (which is a data structure that doesn't allow duplicate entries) from the given array. Node(id=4, fullyQualifiedName=) Using the toMutableSet() function It does not guarantee the preservation of the iteration order of the elements. Return type of toHashSet() is a HashSet.
This function will create a new HashSet (which is a data structure that doesn't allow duplicate entries) from the given array. Node(id=4, fullyQualifiedName=) Using the toHashSet() function } Code Output Node(id=1, fullyQualifiedName=)
It guarantees the preservation of the iteration order of the elements.Ĭode Sample data class Node(val id: Int, val fullyQualifiedName: String). This is the simplest and the best way to remove duplicates from an array in kotlin. This function will create a new Set (which is a data structure that doesn't allow duplicate entries) from the given array. You have a data class called Node: data class Node(val id: Int, val fullyQualifiedName: String)Īnd, an array of Nodes: val nodes = arrayOf( To understand the usage of each function let us consider the following example: It is like an Function approach towards the traditional for-loop way.īoth For loops and ForEach are same when generating output from an array or listįorEach can be more useful if we use it more functional operators.There are a few ways to remove duplicates from an array in kotlin: This will also print the same output like before,Īs you can see that using forEach inplace to for loop make the code more concise and smart.įorEach are used to perfrom action on each and every elements of list Now, in Kotlin we can perform the same operation using ForEach So, if we want to print all the item in the list using for loop, we will use Let's Consider an example, we want to print all the elements in a list But before that let's understand how for loop works. In this blog, we will talk about the ForEach function in Kotlin. We can also use while loops.įor loops are used to get each and evey elements of the Collection, List. Have you ever have iterated through a list or an array in Kotlin or in any programming language ? For loops are traditionally used to do this type of jobs.