Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search object by id in custom type arraylist in kotlin [duplicate]

It can be done easily in Java.

for(Event event:eventList){
if(event.id.equalTo(eventId){
  Event e=new Event();
   e=event;
}
}

I'm doing like this in Kotlin but expected result is not coming

  fun filterList(listCutom: List<Event>?) {
    listCutom!!.forEachIndexed { index, eventid ->
        if (listCutom[index].eventTypeId.equals(eventType)) {
            event= eventid
        }
    }
}

how can I do with Kotlin using filter or forEachIndexed or in another way efficiently?

like image 488
Farhana Naaz Ansari Avatar asked Nov 15 '18 12:11

Farhana Naaz Ansari


People also ask

How do you find duplicates in ArrayList?

One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.

Can ArrayList contain duplicates?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

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.


2 Answers

You can use find extension function on the list:

val eventId = 3
val event: Event? = eventList.find { it.id == eventId }
like image 134
Sergey Avatar answered Sep 28 '22 04:09

Sergey


Why do you use forEachIndexed in Kotlin code, since you don't need the index?
I don't know if the loop could find more than 1 objects and how you use e:

listCutom!!.forEach { event ->
    if (event.id.equalTo(eventId)) {
        val e = event
        //.................
    }
}

with filter:

val filtered = listCutom!!.filter { it.id.equalTo(eventId) }
filtered.forEach { ... }

If you want the indices of the list items that conform to a certain condition:

val indices = listCutom!!.mapIndexedNotNull { index, event ->  if (event.id.equalTo(eventId)) index else null}

then you can iterate through the indices list:

indices.forEach { println(it) }
like image 41
forpas Avatar answered Sep 28 '22 02:09

forpas