How to check if a LinkedList contains a specific element in Kotlin
How to check if a LinkedList contains a specific element in Kotlin.
Here's a step-by-step tutorial on how to check if a LinkedList contains a specific element in Kotlin:
Create a LinkedList:
val linkedList = LinkedList<Int>()Add elements to the LinkedList:
linkedList.add(10)
linkedList.add(20)
linkedList.add(30)Use the
contains()method:val elementToFind = 20
val containsElement = linkedList.contains(elementToFind)Check if the LinkedList contains the specified element:
if (containsElement) {
println("The LinkedList contains $elementToFind.")
} else {
println("The LinkedList does not contain $elementToFind.")
}You can replace
println()with any other desired action based on your requirements.Alternative approach: Iterate through the LinkedList:
val elementToFind = 20
var containsElement = false
for (element in linkedList) {
if (element == elementToFind) {
containsElement = true
break
}
}Check if the element is found:
if (containsElement) {
println("The LinkedList contains $elementToFind.")
} else {
println("The LinkedList does not contain $elementToFind.")
}
Both approaches will give you the same result. Choose the one that suits your code style and requirements.
That's it! Now you know how to check if a LinkedList contains a specific element in Kotlin.