1.查找列表的最后一个元素。 示例
last(listOf(1 , 1 , 2 , 3 , 5 , 8 ))// output: // 8
解决代码:
import com.natpryce.hamkrest.assertion.assertThatimport com.natpryce.hamkrest.equalToimport org.junit.Testfun <T> last(list: List<T>): T = list[list.lastIndex]class P01Test { @Test fun `find the last element of a list`() { assertThat(last(listOf(1 , 1 , 2 , 3 , 5 , 8 )), equalTo(8 )) } @Test(expected = IndexOutOfBoundsException::class) fun `last element in empty list`() { last(listOf<Int >()) } }
2.查找列表的倒数第2个元素。 示例
penultimate(listOf(1 , 1 , 2 , 3 , 5 , 8 ))// output: // 5
解决代码:
package org.kotlin99.listsimport com.natpryce.hamkrest.assertion.assertThatimport com.natpryce.hamkrest.equalToimport org.junit.Testfun <T> penultimate (list: List <T >) = list[list.lastIndex - 1 ]class P02Test { @Test fun `find the last but one element of a list`() { assertThat(penultimate(listOf(1 , 1 , 2 , 3 , 5 , 8 )), equalTo(5 )) } @Test(expected = IndexOutOfBoundsException::class) fun `penultimate element in list smaller than 2`() { penultimate(listOf(1 )) } }
3. 查找列表的第N个元素 nth(2 , listOf(1 , 1 , 2 , 3 , 5 , 8 ))// output: // 2
解决代码:
package org.kotlin99.listsimport com.natpryce.hamkrest.assertion.assertThatimport com.natpryce.hamkrest.equalToimport org.junit.Testimport org.kotlin99.common.tailimport java.util.NoSuchElementExceptiontailrec fun <T> nth (n: Int , list: List <T >) : T { if (n < 0 ) throw IllegalArgumentException() return if (n == 0 ) list.first() else nth(n - 1 , list.tail()) }class P03Test { @Test fun `find the Nth element of a list`() { assertThat(nth(2 , listOf(1 , 1 , 2 , 3 , 5 , 8 )), equalTo(2 )) } @Test(expected = NoSuchElementException::class) fun `Nth element outside of list size`() { nth(100 , listOf(1 , 1 , 2 , 3 , 5 , 8 )) } }
4. 计算列表中的元素个数 示例
length(listOf(1 , 1 , 2 , 3 , 5 , 8 ))// output: // 6
解决代码:
package org.kotlin99.listsimport com.natpryce.hamkrest.assertion.assertThatimport com.natpryce.hamkrest.equalToimport org.junit.Testimport org.kotlin99.common.tailfun <T> length(list: List<T>): Int = if (list.isEmpty()) 0 else 1 + length(list.tail())class P04Test { @Test fun `find the number of elements of a list`() { assertThat(length(listOf<Int >()), equalTo(0 )) assertThat(length(listOf(1 , 1 , 2 , 3 , 5 , 8 )), equalTo(6 )) } }
5. 反转一个列表 示例
reverse(listOf(1 , 1 , 2 , 3 , 5 , 8 ))// output: // [8, 5, 3, 2, 1, 1]
解决代码:
package org.kotlin99.listsimport com.natpryce.hamkrest.assertion.assertThatimport com.natpryce.hamkrest.equalToimport org.junit.Testimport org.kotlin99.common.tailfun <T> reverse(list: List<T>): List<T> = if (list.size <= 1 ) list else reverse(list.tail()) + list.first()class P05Test { @Test fun `reverse a list`() { assertThat(reverse(listOf<Int >()), equalTo(emptyList())) assertThat(reverse(listOf(1 )), equalTo(listOf(1 ))) assertThat(reverse(listOf(1 , 1 , 2 , 3 , 5 , 8 )), equalTo(listOf(8 , 5 , 3 , 2 , 1 , 1 ))) } }
今天给大家分享了Kotlin 的 5 个示例代码练习,大家都学会了吗?我们后面给大家带来更多的 Kotlin 示例