How to get the size of a LinkedList in Kotlin
How to get the size of a LinkedList in Kotlin.
How to Get the Size of a LinkedList in Kotlin
In Kotlin, the LinkedList class is a part of the standard library and provides an implementation of a doubly-linked list. To get the size of a LinkedList, you can use the size property or the count() method. In this tutorial, we will explore both approaches.
1. Using the size Property
The size property returns the number of elements in the LinkedList. Here's how you can use it:
val list = LinkedList<Int>()
list.add(1)
list.add(2)
list.add(3)
val size = list.size
println("Size of the list: $size")
Output:
Size of the list: 3
In the above example, we create a LinkedList, add three elements to it, and then use the size property to get the number of elements in the list.
2. Using the count() Method
The count() method is another way to get the size of a LinkedList. It returns the number of elements matching the given predicate. If no predicate is provided, it returns the total number of elements in the list. Here's how you can use it:
val list = LinkedList<Int>()
list.add(1)
list.add(2)
list.add(3)
val size = list.count()
println("Size of the list: $size")
Output:
Size of the list: 3
In the above example, we create a LinkedList, add three elements to it, and then use the count() method without a predicate to get the number of elements in the list.
3. Handling an Empty LinkedList
If the LinkedList is empty, both the size property and the count() method will return 0. Here's an example:
val list = LinkedList<Int>()
val size = list.size
println("Size of the list: $size")
val count = list.count()
println("Count of the list: $count")
Output:
Size of the list: 0
Count of the list: 0
In the above example, we create an empty LinkedList and then use the size property and the count() method to get the size of the list. Since the list is empty, both methods return 0.
Conclusion
In this tutorial, we learned how to get the size of a LinkedList in Kotlin using the size property and the count() method. Both approaches provide a convenient way to determine the number of elements in the list. Remember to handle the case of an empty list to avoid any potential issues in your code.