Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find an index in Arraylist of custom object based on its specific properties in Kotlin?

Tags:

kotlin

I have an arraylist of event

var approvedEvents = ArrayList<Event>()

the class of Event is like this

class Event() {

    var eventID : String = ""
    var createdBy: String = "" // uid of user creator
    var creatorFullName: String = ""
    var creatorIsVerified : Boolean = false
    var creatorProfilePictureImagePath = ""
    var createdAt : Date = Calendar.getInstance().time
    var hasBeenApproved : Boolean = false
    var title : String = ""
    var speaker : String? = null
    var coordinate : GeoPoint = City.defaultCityCoordinate
    var address : String = ""
    var city : String = ""
    var venue : String = ""

}

so I want to find an index in approvedEvents arraylist that its eventID match selectedEvent.eventID how to do that in Kotlin ? is there specific method that I can use ?

like image 433
Alexa289 Avatar asked Nov 16 '19 06:11

Alexa289


People also ask

How do you find the index of an ArrayList in Kotlin?

In Kotlin, you can use the indexOf() function that returns the index of the first occurrence of the given element, or -1 if the array does not contain the element.

How do you get the index of an element in a list in Kotlin?

In any lists, you can find the position of an element using the functions indexOf() and lastIndexOf() .

How do you search an ArrayList of objects?

Get the array list. Using the for-each loop get each element of the ArrayList object. Verify whether each element in the array list contains the required string. If so print the elements.

How do you sort an ArrayList of objects in Kotlin?

Example: Sort ArrayList of Custom Objects By Property For sorting the list with the property, we use list 's sortedWith() method. The sortedWith() method takes a comparator compareBy that compares customProperty of each object and sorts it. The sorted list is then stored in the variable sortedList .


1 Answers

Use indexOfFirst or indexOfLast to find the index of an item in an ArrayList based on your own criteria like below:

val index = approvedEvents.indexOfFirst{
        it.eventID == selectedEvent.eventID
    }
like image 71
Networks Avatar answered Sep 28 '22 03:09

Networks