Skip to main content

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:

  1. Create a LinkedList:

    val linkedList = LinkedList<Int>()
  2. Add elements to the LinkedList:

    linkedList.add(10)
    linkedList.add(20)
    linkedList.add(30)
  3. Use the contains() method:

    val elementToFind = 20
    val containsElement = linkedList.contains(elementToFind)
  4. 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.

  5. Alternative approach: Iterate through the LinkedList:

    val elementToFind = 20
    var containsElement = false

    for (element in linkedList) {
    if (element == elementToFind) {
    containsElement = true
    break
    }
    }
  6. 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.