【问题标题】:Search object by id in custom type arraylist in kotlin [duplicate]在kotlin的自定义类型arraylist中按id搜索对象[重复]
【发布时间】:2019-04-18 13:44:32
【问题描述】:

在 Java 中可以轻松完成。

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

我在 Kotlin 中这样做,但预期的结果不会出现

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

如何使用 filterforEachIndexed 或以其他方式有效地处理 Kotlin?

【问题讨论】:

  • 您的 Kotlin 与您的 Java 完全不同。
  • 为什么在第一个示例中将 event.id 与 eventId 进行比较,在第二个示例中将 eventTypeId 与 eventType 进行比较?请说出您需要的预期结果
  • @VovaStelmashchuk 我对 lambda 表达式感到困惑。实际上,我想在列表中搜索事件 id 并想要整个对象。

标签: android arrays loops kotlin arraylist


【解决方案1】:

既然不需要索引,为什么在 Kotlin 代码中使用 forEachIndexed
我不知道循环是否可以找到超过 1 个对象以及您如何使用e

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

带过滤器:

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

如果你想要符合某个条件的列表项的索引:

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

然后您可以遍历indices 列表:

indices.forEach { println(it) }

【讨论】:

  • 我们可以通过这些方式找到列表的位置吗?
  • @farhana 查看我编辑的答案
【解决方案2】:

你可以使用find扩展功能就可以了:

val eventId = 3
val event: Event? = eventList.find { it.id == eventId }

【讨论】:

  • @farhana 你的列表已经是一堆 Event 对象了。
猜你喜欢
  • 2015-11-26
  • 2016-06-17
  • 2016-01-07
  • 1970-01-01
  • 2013-11-08
  • 2015-07-10
  • 2013-10-24
  • 2013-11-15
  • 2020-03-21
相关资源
最近更新 更多