-
Notifications
You must be signed in to change notification settings - Fork 1
Kotlin practice #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Kruna1Pate1
wants to merge
1
commit into
develop
Choose a base branch
from
feature/kotlin-practice
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
267 changes: 267 additions & 0 deletions
267
Demo/app/src/main/java/com/krunal/demo/kotlinpractice/collection/CollectionMain.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,267 @@ | ||
| package com.krunal.demo.kotlinpractice.collection | ||
|
|
||
| fun main() { | ||
|
|
||
| // Array | ||
| println("\nArray\n") | ||
| val array = Array(3) { 0 } | ||
| array[0] = 1 | ||
| array[1] = 2 | ||
| array[2] = 3 | ||
| println(array.contentToString()) | ||
|
|
||
|
|
||
| // List | ||
| println("\nList\n") | ||
| val numList = mutableListOf<Int>() | ||
| numList.addAll(array) | ||
| numList.addAll(listOf(4, 3, 2, 5, 3)) | ||
| println(numList) | ||
|
|
||
| // Iterator | ||
| println("\nIterator\n") | ||
| val iterator = numList.iterator().withIndex() | ||
| while (iterator.hasNext()) { | ||
| print("${iterator.next().value}: ${iterator.next().value}") | ||
| } | ||
| println() | ||
|
|
||
| // Progression | ||
| println("\nProgression\n") | ||
| for (i in 1..10 step 2) { | ||
| print("$i ") | ||
| } | ||
| println() | ||
|
|
||
| for (i in 1 until 10 step 2) { | ||
| print("$i ") | ||
| } | ||
| println() | ||
|
|
||
| for (i in 10 downTo 1 step 2) { | ||
| print("$i ") | ||
| } | ||
| println() | ||
|
|
||
| for (i in (10 downTo 1).reversed() step 2) { | ||
| print("$i ") | ||
| } | ||
| println() | ||
|
|
||
| // Sequence | ||
| println("\nSequence\n") | ||
| var charSeq = sequenceOf('a', 'b', 'c', 'd') | ||
| charSeq = ('a'..'k').asSequence() | ||
| charSeq.filter { it in listOf('a', 'e', 'i', 'o', 'u') }.map { print(it); "$it" }.count() | ||
| println() | ||
| val oddNumSeq = generateSequence(2) { it + 2 } | ||
| println(oddNumSeq.take(10).toList()) | ||
| val topTen = generateSequence(1) { if (it < 10) it + 1 else null } | ||
| println(topTen.toList()) | ||
|
|
||
| val oddSeq = sequence { | ||
| yield(1) | ||
| yieldAll(listOf(3, 5, 7)) | ||
| } | ||
| println(oddSeq.toList()) | ||
|
|
||
| // Transformation | ||
| println("\nTransformation\n") | ||
| val numStrList = listOf("1", "2", "3", "4", "5", "6", "7", "4", "8", "2") | ||
| numStrList.map { it.toInt() }.mapIndexedNotNull { index, v -> if (index == 0) null else v } | ||
| .forEach(::print) | ||
| println() | ||
|
|
||
| val numMap = mutableMapOf( | ||
| "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5 | ||
| ) | ||
| val newNumMap: MutableMap<String, String> = mutableMapOf() | ||
| numMap.mapValuesTo(newNumMap) { "${it.value} -> " } | ||
| println(newNumMap) | ||
|
|
||
| println(newNumMap.values zip newNumMap.keys) | ||
| println(newNumMap.values.zip(newNumMap.keys) { value, key -> | ||
| "$value $key" | ||
| }) | ||
|
|
||
| println(numStrList.associateWith { it.length }) | ||
| println(numStrList.withIndex().associateBy { it.index }.mapValues { it.value.value }) | ||
|
|
||
| val numberSets = listOf(setOf(1, 2, 3), setOf(4, 5, 6), setOf(1, 2)) | ||
| println(numberSets.flatten()) | ||
| println(numberSets.flatMap { it }) | ||
|
|
||
| println(numStrList.joinToString( | ||
| separator = " -> ", | ||
| prefix = "start: ", | ||
| postfix = " :end", | ||
| limit = 4, | ||
| truncated = "more..." | ||
| ) { "${it}x" }) | ||
|
|
||
| // Filtering | ||
| println("\nFiltering\n") | ||
|
|
||
| val nums = (1..20).toMutableList() | ||
| println("even: ${nums.filter { it % 2 == 0 }}") | ||
| println("odd: ${nums.filterNot { it % 2 == 0 }}") | ||
| val nullableNums = mutableListOf(null, 1, 2, null) | ||
| println(nullableNums.filterNotNull()) | ||
| println("large: ${nums.filterIndexed { index, _ -> index > 10 }}") | ||
|
|
||
| val anyType = listOf(null, 1, "two", 3.0, "four") | ||
| println("strings: ${anyType.filterIsInstance<String?>()}") | ||
|
|
||
| val (odd, even) = nums.partition { it % 2 != 0 } | ||
| println("$odd, $even") | ||
|
|
||
| println("any > 20 ${nums.any { it > 20 }}") | ||
| println("none > 20 ${nums.none { it > 20 }}") | ||
| println("all < 5 ${nums.all { it > 20 }}") | ||
|
|
||
| // Plus and minus operators | ||
| println("\nPlus and minus operators\n") | ||
| val l1 = listOf(1, 3, 5) | ||
| val l2 = listOf(2, 4, 5) | ||
| println(l1 + l2 + "str" - 5) | ||
|
|
||
| // Grouping | ||
| println("\nGrouping\n") | ||
| println(numStrList.groupBy { if (it.toInt() % 2 == 0) "even" else "odd" }) | ||
| println(numStrList.groupingBy { if (it.toInt() % 2 == 0) "even" else "odd" }.eachCount()) | ||
|
|
||
| // Retrieve collection parts | ||
| println("\nRetrieve collection parts\n") | ||
| val numbers = mutableListOf("one", "two", "three", "four", "five", "six") | ||
| println(nums.slice(5..10)) | ||
| println(nums.slice(5 until 10 step 2)) | ||
| println(nums.slice(setOf(2, 3, 5))) | ||
| println(nums.subList(5, 10)) | ||
|
|
||
| println(nums.take(5)) | ||
| println(nums.takeLast(5)) | ||
| println(nums.drop(5)) | ||
| println(nums.dropLast(5)) | ||
|
|
||
| println(nums.takeWhile { it < 10 }) | ||
| println(nums.takeLastWhile { it < 10 }) | ||
| println(nums.dropWhile { it < 10 }) | ||
| println(nums.dropLastWhile { it > 10 }) | ||
|
|
||
| println(nums.chunked(5)) | ||
| println(nums.windowed(5, step = 3)) | ||
| println(nums.windowed(5, step = 3, partialWindows = true)) | ||
| println(nums.zipWithNext()) | ||
|
|
||
| // Retrieve single elements | ||
| println("\nRetrieve single elements\n") | ||
| val numSet = numbers.toSet() | ||
| println(numSet.elementAt(4)) | ||
| // println(numSet.get(4)) | ||
| println(numSet.elementAtOrElse(10) { it * 10 }) | ||
| println(numSet.elementAtOrNull(10)) | ||
|
|
||
| println("${numSet.first()} -> ${numSet.last { it.length > 4 }}") | ||
| println("${nums.firstOrNull { it > 10 }} -> ${nums.findLast { it > 15 }}") | ||
|
|
||
| println(numSet.random()) | ||
| println(emptyList<String>().randomOrNull()) | ||
| println(emptyList<String>().isNotEmpty()) | ||
|
|
||
| // Ordering | ||
| println("\nOrdering\n") | ||
| val randomList = nums.shuffled() | ||
| println(randomList) | ||
| println(randomList.sortedDescending()) | ||
| println(randomList.sortedBy { it % 5 }) | ||
| println(randomList.sortedWith { i, j -> (i % 5) - (j % 5) }) | ||
|
|
||
| val revNum1 = numbers.reversed() | ||
| val revNum2 = numbers.asReversed() | ||
| println("$revNum1 $revNum2") | ||
| numbers.removeLast() | ||
| revNum2.removeLast() | ||
| println("$revNum1 $revNum2") | ||
| println(numbers) | ||
|
|
||
| // Aggregate operations | ||
| println("\nAggregate operations\n") | ||
| println(setOf(2, 5, 3, 1).min()) | ||
| println(emptySet<Int>().maxOrNull()) | ||
| println(nums.average()) | ||
| println(nums.count()) | ||
| println(nums.sum()) | ||
| println(nums.sumOf { it * 2 }) | ||
|
|
||
| println(nums.fold(0) { acc, i -> acc + i }) | ||
| println(nums.reduce { acc, i -> acc + i }) | ||
| println(nums.foldRight(100) { acc, i -> acc - i }) | ||
| println(nums.reduceRight { acc, i -> acc - i }) | ||
| println(nums.runningFold(0) { acc, i -> acc + i }) | ||
|
|
||
| // Collection write operations | ||
| println("\nCollection write operations\n") | ||
| val mNums = nums.toMutableList() | ||
| mNums.clear() | ||
| println(mNums) | ||
| println(mNums.addAll((1..10))) | ||
| mNums += 100 | ||
| mNums -= 4..7 | ||
| mNums.addAll(listOf(5, 5, 10, 9, 9, 4, 3, 2)) | ||
| mNums.add(5) | ||
| println(mNums) | ||
| mNums.remove(10) | ||
| mNums.removeAll(listOf(5)) | ||
| println(mNums) | ||
| mNums.retainAll { it % 2 == 0 } | ||
| println(mNums) | ||
| mNums[mNums.lastIndex] = 101 | ||
| println(mNums) | ||
| val mList = mutableListOf(1, 2, 3) | ||
| mList.fill(0) | ||
| println(mList) | ||
|
|
||
| // Find element positions | ||
| println("\nFind element positions\n") | ||
| println(mNums.indexOf(9)) | ||
| println(mNums.lastIndexOf(2)) | ||
| println(mNums.indexOfFirst { it > 8 }) | ||
|
|
||
| println(numbers.binarySearch("two")) | ||
| println(numbers.binarySearch("z")) | ||
| println(numbers.binarySearch("two", 0, 2)) | ||
|
|
||
| // Set-specific operations | ||
| println("\nSet-specific operations\n") | ||
| val numSet1 = mutableSetOf(1, 2, 3, 4, 5, 6) | ||
| val numSet2 = mutableSetOf(4, 5, 6, 7, 8, 9) | ||
| println("union: ${numSet1 union numSet2}") | ||
| println("intersect: ${numSet1 intersect numSet2}") | ||
| println("subtract: ${numSet1 subtract numSet2}") | ||
|
|
||
| // Map-specific operations | ||
| println("\nMap-specific operations\n") | ||
| println("${numMap.keys} ${numMap.values}") | ||
| println(numMap.entries) | ||
| println(numMap["one"]) | ||
| println(numMap["nine"]) | ||
| println(numMap.getOrDefault("nine", 9)) | ||
| println(numMap.getOrElse("nine") { 9 }) | ||
| val two by numMap | ||
| // val nine by numMap | ||
| println(two) | ||
| numMap += ("ten" to 10) | ||
| println(numMap) | ||
| numMap["nine"] = 9 | ||
| numMap.remove("ten") | ||
| numMap.remove("nine", 10) | ||
| numMap -= "five" | ||
| println(numMap) | ||
|
|
||
| // Custom quadruple | ||
| println("\nCustom quadruple\n") | ||
| val quadruple: Quadruple<String, Char, Any, Number> = Quadruple("A", 'b', true, 10) | ||
| println(quadruple) | ||
| println(quadruple.first) | ||
| println(quadruple.toList()) | ||
| } | ||
12 changes: 12 additions & 0 deletions
12
Demo/app/src/main/java/com/krunal/demo/kotlinpractice/collection/Quadruple.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.krunal.demo.kotlinpractice.collection | ||
|
|
||
| import java.io.Serializable | ||
|
|
||
| data class Quadruple<out A, out B, out C, out D>( | ||
| val first: A, val second: B, val third: C, val fourth: D | ||
| ) : Serializable { | ||
|
|
||
| override fun toString() = "($first, $second, $third, $fourth)" | ||
| } | ||
|
|
||
| fun <T> Quadruple<T, T, T, T>.toList() = listOf(first, second, third, fourth) |
96 changes: 96 additions & 0 deletions
96
Demo/app/src/main/java/com/krunal/demo/kotlinpractice/controlflow/ConditionAndLoop.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| package com.krunal.demo.kotlinpractice.controlflow | ||
|
|
||
| import kotlin.random.Random | ||
|
|
||
| fun main() { | ||
| // if-else | ||
| val a = 5 | ||
| val b = 7 | ||
| val max = if (a > b) a else b | ||
| println("max $max") | ||
|
|
||
| val name: String? = "KP" | ||
| if (name != null) { | ||
| println(name) | ||
| } | ||
|
|
||
| // when | ||
| val char = 'a' | ||
| val type = when (char) { | ||
| 'a', 'e', 'i', 'o', 'u' -> "small vowel" | ||
| 'A', 'E', 'I', 'O', 'U' -> "capital vowel" | ||
| in 'a'..'z' -> "small constant" | ||
| in 'A'..'Z' -> "capital constant" | ||
| else -> "invalid char" | ||
| } | ||
| println("$char is $type") | ||
|
|
||
| val password = "Krunal@123" | ||
| when { | ||
| password.isNullOrEmpty() -> println("password can't be empty") | ||
| password.length < 5 -> println("password is too short") | ||
| password.contains("Krunal") -> println("password should not contain name") | ||
| else -> println("valid password") | ||
| } | ||
|
|
||
| // Loops | ||
| for (i in 1 until 11) { | ||
| print(i) | ||
| } | ||
| println() | ||
|
|
||
| for (i in 10 downTo 0 step 3) { | ||
| print(i) | ||
| } | ||
| println() | ||
|
|
||
| var str = "abcba" | ||
| while (str.isNotEmpty()) { | ||
| str = str.removeRange(str.length - 1, str.length) | ||
| } | ||
| println("str $str") | ||
|
|
||
| do { | ||
| val num = Random.nextInt(50, 200) | ||
| println("num: $num") | ||
| } while (num < 100) | ||
|
|
||
| // Break & Continue | ||
| small@ for (i in 1..100) { | ||
| if (i % 2 == 0) continue | ||
| print(i) | ||
| if (i > 10) break@small | ||
| } | ||
|
|
||
| // Custom double range | ||
| for (i in 1.1..2.2) { | ||
| println(i) | ||
| } | ||
| } | ||
|
|
||
| operator fun Double.rangeTo(end: Double): DoubleClosedRange { | ||
|
|
||
| return object : DoubleClosedRange { | ||
| override val endInclusive: Double | ||
| get() = end | ||
| override val start: Double | ||
| get() = this@rangeTo | ||
|
|
||
| private var current = this@rangeTo | ||
|
|
||
| override fun iterator(): Iterator<Double> { | ||
| return object : Iterator<Double> { | ||
| override fun hasNext(): Boolean { | ||
| return current <= end | ||
| } | ||
|
|
||
| override fun next(): Double { | ||
| current += 0.1 | ||
| return current | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| interface DoubleClosedRange : ClosedRange<Double>, Iterable<Double> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤖 OpenAI
There are no issues with the code logic or syntax. However, there are some suggestions for improving the documentation:
These changes will make the code easier to understand and maintain in the future.