Skip to content

Commit

Permalink
[KTLN-495] Add Sammples (Baeldung#612)
Browse files Browse the repository at this point in the history
  • Loading branch information
LeoColman authored Sep 21, 2023
1 parent 59389de commit 868ca23
Showing 1 changed file with 60 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.baeldung.indexof

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test


class IndexOfTests {

@Test
fun `Find index using indexOf`() {
val numbers = arrayOf(1, 2, 3, 4, 5)
val elementToFind = 3
val index = numbers.indexOf(elementToFind)

assertEquals(2, index)
}

@Test
fun `Find index of first`() {
val numbers = arrayOf(1, 2, 3, 4, 3, 5)
val elementToFind = 3
val index = numbers.indexOfFirst { it == elementToFind }

assertEquals(2, index)
}

@Test
fun `Find last index of element`() {
val numbers = arrayOf(1, 2, 3, 4, 3, 5)
val elementToFind = 3
val lastIndex = numbers.lastIndexOf(elementToFind)

assertEquals(4, lastIndex)
}

@Test
fun `Find index of last`() {
val numbers = arrayOf(1, 2, 3, 4, 3, 5)
val elementToFind = 3
val index = numbers.indexOfLast { it == elementToFind }

assertEquals(4, index)
}

@Test
fun `Find indices using loop`() {
val numbers = arrayOf(1, 2, 3, 4, 3, 5)
val elementToFind = 3
val indices = mutableListOf<Int>()

for (i in numbers.indices) {
if (numbers[i] == elementToFind) {
indices.add(i)
}
}

assertEquals(listOf(2, 4), indices)
}

}

0 comments on commit 868ca23

Please sign in to comment.