How to get the last value of an ArrayList in kotlin? - arraylist

How to get the last item of an ArrayList in kotlin?
I have a list like
val myList = listOf("item1", "item2", "item3")
I want to get the last item of myList

There's last() method, created exactly for this purpose.
myList.last()

Related

How to create list with float values in kotlin

I am a beginner in this field, I want to create a list of float values in kotlin
Example: In python
myList=[]
mylist.append(1.5)
mylist.append(2.5)
but how to do this in kotlin
We need to specify the list element's data type (Float in this case) when initializing empty mutable list using mutableListOf().
val myList = mutableListOf<Float>()
myList.add(1.5f)
myList.add(2.5f)
Use the listOf function:
val listOfFloats: List<Float> = listOf(1.1f, 2.2f, 3.3f)
In kotlin you can make a list like this
var myList: List<Int> = listOf<Int>(1, 2, 7, 9);
But if you want to push an item to the list you need to make it a mutable list. So I would say that you use a MutableList instead of a List
So it looks like this
var myList : MutableList<Int> = mutableListOf<Int>(); //You can add initial values inside the parentheses
myList.add(10);
myList.add(20);

Dynamically add list to a list in Kotlin

I have:
var myList: MutableList<MutableList<Int>>
and I want to dynamically create a list (i, j) which are Int and it is to the myList.
I tried
myList.add(mutableListOf(i,j))
But it doesn't work.
Firstly I get error: variable 'myList' must be initialized
And I am not sure that's the right way to make a list on the go and add it to a list of lists
As the error mentions, you have to initialize the list before using it.
var myList: MutableList<MutableList<Int>> with this you just declare its type.
var myList = mutableListOf<MutableList<Int>>() with this you have empty list. After that you can freely add another list inside it as an element.
initialize the list
var myList: MutableList<Int> = ArrayList()

sortedBy() selector not sorting List

I have a sortedBy{} statement which intends to sort a List by the length of the String elements:
var animals: List<String> = listOf("tiger", "cat", "dragon", "elephant")
fun strLength(it: String) = it.length
animals.sortedBy { strLength(it) }
animals.forEach {println(it)}
However it only prints the initial order. Any idea why?
You have to assign the output of sortedBy.
animals = animals.sortedBy { strLength(it) }
Because, like many other functions in Kotlin, sortedBy doesn’t mutate the input & honour immutability. So it returns a new collection. So it mitigates side-effects. Kotlin encourages this immutable approach. However, there are mutable counterparts of these collections if required.
sortedBy does not sort the list, instead it returns a new list which has the elements sorted. If you don't want a new list, simply use sortBy.

Why can I instantiate a MutableList as a val in Kotlin (and also add elements to it)?

I'm just in the very early stages of learning Kotlin so I played a video that shows many of the common Kotlin idioms: Kotlin tutorial
Just at the 1:03:10 point in the video, the presenter discusses mutable and immutable collections. As you can see in the video, he creates a MutableList with the var keyword and an immutable List with the val keyword. I was curious to see what error would occur if I tried to use val with a MutableList; I assumed that would not be permissible and that IDEA would display a message to that effect but it gave me no error message. Then I added an element to the MutableList and that didn't cause an error either! When I displayed the last element of the MutableList, it displayed the element that I'd added so it not only failed to give me an error, it successfully added an element to something I thought was immutable.
Why does my code work? I can't believe a total Kotlin beginner like me found a fundamental bug in Kotlin so there must be something else going on. Can someone explain?
Here's my code:
val list3: MutableList<Int> = mutableListOf(6,7,8)
list3.add(5)
println("list3 last item: ${list3.last()}")
The println() statement displays:
list3 last item: 5
val only means that the variable itself cannot be re-assigned. It does not say anything about the object in that variable being mutable or not.
You would get an error if you tried to do
val list3: MutableList<Int> = mutableListOf(6,7,8)
list3 = mutableListOf(1,2,3) // cannot re-assign to val
val means value, so you can assign that val to an object just once, it's same like final keyword in Java. When you try to reassign the val again, then an error will be occurred.
val list3: MutableList<Int> = mutableListOf(6,7,8)
list3.add(5)
println("list3 last item: ${list3.last()}")
in the example above, you weren't assign list3 a new object, instead you just mutate/add new value of the list.
val list3: MutableList<Int> = mutableListOf(6,7,8)
list3 = mutableListOf(1,2,3)
in the example above, then the error will be occurred because we try to assign list3 a new instance of mutableList
Hope it helps

copy one arraylist to another arraylist in kotlin

I am trying to copy one ArrayList to another ArrayList in Kotlin
1st ArrayList:
private var leadList1: ArrayList<Lead> = ArrayList()
2nd ArrayList:
val leadList2: ArrayList<Lead?>?
I tried to use addAll(). leadList1.addAll(leadList2)
But its not working.
Error showing:
Required: Collection<Lead>
Found: kotlin.collections.ArrayList<Lead?>?
This isn't safe to do, because your first list can only contain objects of type Lead, while your second one has Lead? as its type parameter, meaning that it might contain null values. You can't add those to the first list.
The solution for this problem will depend on your context, but you can either let the first list contain nullable elements too:
private var leadList1: ArrayList<Lead?> = ArrayList()
Or you can add only the non-null elements of the second list to the first one:
leadList1.addAll(leadList2.filterNotNull())
And in either case, you'll have to perform a null check on leadList2, because the entire list itself is marked as potentially null as well, signified by the last ? of the type ArrayList<Lead?>?.
if (leadList2 != null) {
leadList1.addAll(leadList2.filterNotNull())
}
You can simply pass another List instance into the constructor of your new List
val originalList = arrayListOf(1,2,3,4,5)
val orginalListCopy = ArrayList(originalList)
Do this:
leadList1.addAll(leadList2.orEmpty().filterNotNull())
And to filter by property you can do like this:
leadList1.addAll(leadList2.orEmpty().filter { item -> item?.type == YourTypeString })