import java.util.LinkedList
import java.util.TreeSet
import java.util.TreeMap
import java.util.HashSet
import java.util.HashMap
import java.util.LinkedHashSet
import java.util.LinkedHashMap
class Version1 {
fun initializeArrayWithInt() {
println("====================================================")
println("Hello from immutable array (pre-filled array)")
val carArray = arrayOf(0, 0, 3, 4, 5) // ✅ Array with 5 Int elements
carArray.set(0, 1)
carArray[1] = 2
for (i in carArray) {
println(i)
}
println("====================================================")
println("Hello from mutable array (Constructor)")
val car = Array(5) { 0 } // ✅ Creates array of size 5 filled with 0s
car.set(0, 1)
car[1] = 2
for (i in car) {
println(i)
}
}
fun initializeLists() {
println("====================================================")
val immutableList = listOf<String>("Hello from immutable list") // Immutable empty list
println(immutableList)
val mutableList = mutableListOf<String>() // Mutable empty list
mutableList.add("Hello from mutable list")
println(mutableList)
val arrayList = ArrayList<String>() // Resizable array
arrayList.add("Hello from Resizable array")
println(arrayList)
val linkedList = LinkedList<String>() // Fast insert/remove
linkedList.add("Hello from LinkedList")
println(linkedList)
}
fun initializeSets() {
println("====================================================")
val immutableSet = setOf<String>("Hello from immutable set") // Immutable empty set
println(immutableSet)
val mutableSet = mutableSetOf<String>() // Mutable empty set
mutableSet.add("Hello from mutable set")
println(mutableSet)
val hashSet = HashSet<String>() // Unordered unique elements
hashSet.add("Hello from HashSet")
println(hashSet)
val treeSet = TreeSet<String>() // Sorted unique elements
treeSet.add("Hello from TreeSet")
println(treeSet)
val linkedHashSet = LinkedHashSet<String>() // Preserves insertion order
linkedHashSet.add("Hello from LinkedHashSet")
println(linkedHashSet)
}
fun initializeMaps() {
println("====================================================")
val immutableMap = mapOf<Int, String>(1 to "Hello from immutable map") // Immutable empty map
println(immutableMap)
val mutableMap = mutableMapOf<String, Int>() // Mutable empty map
mutableMap.put("Hello from mutable map", 1)
println(mutableMap)
val hashMap = HashMap<String, Int>() // Unordered key-value pairs
hashMap.put("Hello from hashmap", 1)
println(hashMap)
val treeMap = TreeMap<String, Int>() // Sorted by keys
treeMap.put("Hello from TreeMap", 1)
println(treeMap)
val linkedHashMap = LinkedHashMap<String, Int>() // Preserves insertion order
linkedHashMap.put("Hello from LinkedHashMap", 1)
println(linkedHashMap)
}
}
class Version2 {
fun declareArrayTypes() {
var stringArray: Array<String> // Declared but not initialized
}
fun declareListTypes() {
var immutableList: List<String> // Declared List
var mutableList: MutableList<String> // Declared MutableList
var arrayList: ArrayList<String> // Declared ArrayList
var linkedList: LinkedList<String> // Declared LinkedList
}
fun declareSetTypes() {
var immutableSet: Set<String> // Declared Set
var mutableSet: MutableSet<String> // Declared MutableSet
var hashSet: HashSet<String> // Declared HashSet
var treeSet: TreeSet<String> // Declared TreeSet
var linkedHashSet: LinkedHashSet<String> // Declared LinkedHashSet
}
fun declareMapTypes() {
var immutableMap: Map<String, String> // Declared Map
var mutableMap: MutableMap<String, String> // Declared MutableMap
var hashMap: HashMap<String, String> // Declared HashMap
var treeMap: TreeMap<String, String> // Declared TreeMap
var linkedHashMap: LinkedHashMap<String, String> // Declared LinkedHashMap
}
fun initializeArrayTypes() {
println("====================================================")
println("Array Type Initialization")
var stringArray: Array<String> = arrayOf("Kotlin", "Array", "Example")
println("StringArray: ${stringArray.contentToString()}")
}
fun initializeListTypes() {
println("====================================================")
println("List Type Initialization")
var immutableList: List<String> = listOf("Item1", "Item2", "Item3")
println("Immutable List: $immutableList")
var mutableList: MutableList<String> = mutableListOf("Item1", "Item2")
mutableList.add("Item3")
println("Mutable List: $mutableList")
var arrayList: ArrayList<String> = arrayListOf("ArrayItem1", "ArrayItem2")
arrayList.add("ArrayItem3")
println("ArrayList: $arrayList")
var linkedList: LinkedList<String> = linkedListOf("LinkedItem1", "LinkedItem2")
linkedList.add("LinkedItem3")
println("LinkedList: $linkedList")
}
fun initializeSetTypes() {
println("====================================================")
println("Set Type Initialization")
var immutableSet: Set<String> = setOf("SetItem1", "SetItem2", "SetItem3")
println("Immutable Set: $immutableSet")
var mutableSet: MutableSet<String> = mutableSetOf("MutableSetItem1", "MutableSetItem2")
mutableSet.add("MutableSetItem3")
println("Mutable Set: $mutableSet")
var hashSet: HashSet<String> = hashSetOf("HashItem1", "HashItem2")
hashSet.add("HashItem3")
println("HashSet: $hashSet")
var treeSet: TreeSet<String> = TreeSet<String>()
treeSet.add("TreeItem3")
treeSet.add("TreeItem1")
treeSet.add("TreeItem2")
println("TreeSet (Sorted): $treeSet")
var linkedHashSet: LinkedHashSet<String> = linkedSetOf("LinkedSetItem1", "LinkedSetItem2")
linkedHashSet.add("LinkedSetItem3")
println("LinkedHashSet (Insertion Order): $linkedHashSet")
}
fun initializeMapTypes() {
println("====================================================")
println("Map Type Initialization")
var immutableMap: Map<String, String> = mapOf("key1" to "value1", "key2" to "value2")
println("Immutable Map: $immutableMap")
var mutableMap: MutableMap<String, String> = mutableMapOf("key1" to "value1", "key2" to "value2")
mutableMap["key3"] = "value3"
println("Mutable Map: $mutableMap")
var hashMap: HashMap<String, String> = hashMapOf("hashKey1" to "hashValue1", "hashKey2" to "hashValue2")
hashMap["hashKey3"] = "hashValue3"
println("HashMap: $hashMap")
var treeMap: TreeMap<String, String> = TreeMap<String, String>()
treeMap["treeKey3"] = "treeValue3"
treeMap["treeKey1"] = "treeValue1"
treeMap["treeKey2"] = "treeValue2"
println("TreeMap (Sorted by Keys): $treeMap")
var linkedHashMap: LinkedHashMap<String, String> = linkedMapOf("linkedKey1" to "linkedValue1", "linkedKey2" to "linkedValue2")
linkedHashMap["linkedKey3"] = "linkedValue3"
println("LinkedHashMap (Insertion Order): $linkedHashMap")
}
fun demonstrateCollectionOperations() {
println("====================================================")
println("Collection Operations Demonstration")
// List operations
val numbers = mutableListOf(1, 2, 3, 4, 5)
println("Original List: $numbers")
numbers.add(6)
println("After adding 6: $numbers")
numbers.remove(3)
println("After removing 3: $numbers")
println("List size: ${numbers.size}")
println("Contains 4: ${numbers.contains(4)}")
// Set operations
val uniqueNumbers = mutableSetOf(1, 2, 3, 4, 5)
uniqueNumbers.add(3) // Duplicate, won't be added
println("\nSet (duplicates ignored): $uniqueNumbers")
println("Set size: ${uniqueNumbers.size}")
// Map operations
val person = mutableMapOf("name" to "John", "age" to "30", "city" to "New York")
println("\nOriginal Map: $person")
person["country"] = "USA"
println("After adding country: $person")
println("Name: ${person["name"]}")
println("Contains 'age' key: ${person.containsKey("age")}")
// Iteration examples
println("\nIterating through list:")
for ((index, value) in numbers.withIndex()) {
println("Index $index: $value")
}
println("\nIterating through map:")
for ((key, value) in person) {
println("$key: $value")
}
}
fun comparingCollectionPerformance() {
println("====================================================")
println("Collection Performance Comparison")
// ArrayList vs LinkedList
val arrayListPerf = ArrayList<Int>()
val linkedListPerf = LinkedList<Int>()
for (i in 1..1000) {
arrayListPerf.add(i)
linkedListPerf.add(i)
}
println("ArrayList with 1000 elements: ${arrayListPerf.size} items")
println("LinkedList with 1000 elements: ${linkedListPerf.size} items")
println("ArrayList get(500): ${arrayListPerf[500]}")
println("LinkedList get(500): ${linkedListPerf[500]}")
// HashSet vs TreeSet
val hashSetPerf = HashSet<String>()
val treeSetPerf = TreeSet<String>()
val items = listOf("zebra", "apple", "banana", "mango", "pear")
hashSetPerf.addAll(items)
treeSetPerf.addAll(items)
println("\nHashSet (unordered): $hashSetPerf")
println("TreeSet (sorted): $treeSetPerf")
// HashMap vs TreeMap
val hashMapPerf = HashMap<String, Int>()
val treeMapPerf = TreeMap<String, Int>()
mapOf("zebra" to 1, "apple" to 2, "banana" to 3).forEach { (k, v) ->
hashMapPerf[k] = v
treeMapPerf[k] = v
}
println("\nHashMap: $hashMapPerf")
println("TreeMap (sorted by keys): $treeMapPerf")
}
}
fun main() {
val Runner1 = Version1()
val Runner2 = Version2()
// Version1 demonstrations
Runner1.initializeArrayWithInt()
Runner1.initializeLists()
Runner1.initializeSets()
Runner1.initializeMaps()
// Version2 demonstrations
Runner2.initializeArrayTypes()
Runner2.initializeListTypes()
Runner2.initializeSetTypes()
Runner2.initializeMapTypes()
Runner2.demonstrateCollectionOperations()
Runner2.comparingCollectionPerformance()
}A comprehensive educational program demonstrating all Kotlin collection types, their initialization methods, practical operations, and performance characteristics.
- Overview
- Project Structure
- Features
- Getting Started
- Collection Types Covered
- Usage Examples
- Classes and Methods
- Output Description
- Performance Comparisons
- Prerequisites
- Installation
- Running the Program
- Learning Outcomes
This project provides a complete educational resource for learning Kotlin's collection framework. It covers all major collection types including Arrays, Lists, Sets, and Maps, demonstrating both immutable and mutable variants with practical examples and performance comparisons.
The program is organized into two main classes (Version1 and Version2) that progressively demonstrate different aspects of Kotlin collections, from basic initialization to advanced operations.
KotlinCollectionsFrameworkCompleteGuide/
├── README.md
├── src/
│ └── main/
│ └── kotlin/
│ └── collections/
│ └── CollectionsDemo.kt
└── docs/
└── CollectionsGuide.md
✅ Comprehensive Coverage: Demonstrates all Kotlin collection types ✅ Dual Approach: Shows both declaration and initialization patterns ✅ Practical Examples: Real-world usage scenarios ✅ Performance Analysis: Compares different collection implementations ✅ Educational Focus: Inline comments and clear output formatting ✅ Version Control: Two classes showing progression from basic to advanced ✅ Operation Demos: Shows common collection operations (add, remove, iterate) ✅ Type Safety: Demonstrates Kotlin's type-safe collection framework
- Kotlin 1.5 or higher
- JDK 8 or higher
- IntelliJ IDEA or any Kotlin-compatible IDE (optional)
- Clone or Download the repository
git clone https://github.com/yourusername/KotlinCollectionsFrameworkCompleteGuide.git
cd KotlinCollectionsFrameworkCompleteGuide- Open in your preferred IDE or text editor
Using Command Line:
kotlinc CollectionsDemo.kt -include-runtime -d CollectionsDemo.jar
java -jar CollectionsDemo.jarUsing IDE:
- Open the project in IntelliJ IDEA or Android Studio
- Click the "Run" button or press
Shift + F10
- Fixed-size collections with fast random access
- Pre-filled arrays using
arrayOf() - Constructor-based arrays with default values
- Immutable List:
listOf()- Cannot be modified - Mutable List:
mutableListOf()- Dynamic size - ArrayList: Resizable array-backed list with O(1) access
- LinkedList: Doubly-linked list with efficient insertion/removal
- Immutable Set:
setOf()- Cannot be modified - Mutable Set:
mutableSetOf()- Dynamic size - HashSet: Unordered unique elements with O(1) operations
- TreeSet: Automatically sorted unique elements
- LinkedHashSet: Maintains insertion order
- Immutable Map:
mapOf()- Cannot be modified - Mutable Map:
mutableMapOf()- Dynamic entries - HashMap: Unordered key-value pairs with O(1) operations
- TreeMap: Automatically sorted by keys
- LinkedHashMap: Maintains insertion order of entries
// Pre-filled array
val carArray = arrayOf(0, 0, 3, 4, 5)
// Array with constructor
val car = Array(5) { 0 } // Size 5, all elements are 0// Immutable list
val immutableList = listOf("Item1", "Item2", "Item3")
// Mutable list
val mutableList = mutableListOf("Item1", "Item2")
mutableList.add("Item3")// HashSet - unordered
val hashSet = hashSetOf("Item1", "Item2")
// TreeSet - sorted automatically
val treeSet = TreeSet<String>()
treeSet.add("Zebra")
treeSet.add("Apple") // Will be sorted: [Apple, Zebra]// Immutable map
val immutableMap = mapOf("key1" to "value1", "key2" to "value2")
// HashMap - unordered
val hashMap = hashMapOf("key1" to "value1")
// TreeMap - sorted by keys
val treeMap = TreeMap<String, String>()
treeMap["key3"] = "value3"
treeMap["key1"] = "value1" // Will be sorted by key// List operations
val numbers = mutableListOf(1, 2, 3, 4, 5)
numbers.add(6)
numbers.remove(3)
println(numbers.size)
println(numbers.contains(4))
// Map operations
val person = mutableMapOf("name" to "John", "age" to "30")
person["city"] = "New York"
println(person["name"])
println(person.containsKey("age"))
// Iteration
for ((index, value) in numbers.withIndex()) {
println("Index $index: $value")
}
for ((key, value) in person) {
println("$key: $value")
}Basic initialization and demonstration of collection types:
initializeArrayWithInt(): Demonstrates array creation and modificationinitializeLists(): Shows all list types and their basic usageinitializeSets(): Demonstrates all set implementationsinitializeMaps(): Shows all map types
Advanced initialization, operations, and comparisons:
declareArrayTypes(): Shows array type declarationsdeclareListTypes(): Shows list type declarationsdeclareSetTypes(): Shows set type declarationsdeclareMapTypes(): Shows map type declarationsinitializeArrayTypes(): Initializes array types with valuesinitializeListTypes(): Initializes list types with valuesinitializeSetTypes(): Initializes set types with valuesinitializeMapTypes(): Initializes map types with valuesdemonstrateCollectionOperations(): Shows practical operationscomparingCollectionPerformance(): Compares different implementations
The program produces organized console output divided into sections:
-
Version1 Output: Basic collection initialization
- Array demonstrations
- List examples
- Set examples
- Map examples
-
Version2 Output: Advanced features
- Type initialization
- Practical operations
- Performance comparisons
- Iteration examples
Each section is separated by a line of equals signs (====) for clarity.
- ArrayList: O(1) random access, O(n) insertion/deletion
- LinkedList: O(n) random access, O(1) insertion/deletion at ends
- HashSet: Unordered, O(1) average operations
- TreeSet: Sorted, O(log n) operations
- HashMap: Unordered, O(1) average operations
- TreeMap: Sorted by keys, O(log n) operations
After studying this program, you will understand:
- How to create and initialize all Kotlin collection types
- The differences between mutable and immutable collections
- When to use each collection type based on use case
- How to perform common operations on collections
- Performance characteristics of different implementations
- Best practices for collection usage in Kotlin
- Iteration patterns for different collection types
- Type safety in Kotlin's collection framework
| Collection | Use Case | Performance | Ordering |
|---|---|---|---|
| ArrayList | Random access needed | O(1) access | N/A |
| LinkedList | Frequent insertions/deletions at ends | O(1) add/remove ends | Insertion order |
| HashSet | Fast uniqueness checks | O(1) average | None |
| TreeSet | Sorted unique elements needed | O(log n) | Sorted |
| HashMap | Fast key-value lookup | O(1) average | None |
| TreeMap | Sorted key-value pairs | O(log n) | Sorted by keys |
- Prefer immutable collections by default: Use
listOf(),setOf(),mapOf()unless you need modification - Choose the right implementation: Use
HashMapfor speed,TreeMapfor sorted data - Consider insertion patterns: Use
LinkedListif you frequently add/remove from ends - Leverage Kotlin's DSL: Use helper functions like
mutableListOf(),hashMapOf(),linkedMapOf() - Use type inference: Kotlin can infer types, reducing verbosity
- Remember immutability: Immutable collections are safer and prevent bugs
- Official Kotlin Collections Documentation
- Kotlin Collections API Reference
- Java Collections Framework
Contributions are welcome! Feel free to:
- Add more examples
- Improve documentation
- Add performance benchmarks
- Create additional demonstration programs
This project is licensed under the MIT License - see the LICENSE file for details.
Created as an educational resource for learning Kotlin collections.
- v1.0 - Initial release with comprehensive collection demonstrations
- v1.1 - Added performance comparisons and advanced operations
For questions or issues, please open an issue on the GitHub repository or contact the maintainers.
Happy Learning! 🚀
Master Kotlin collections and write more efficient, type-safe code!