在我的应用程序中,我有2列表,或者列表之间的一些项目相同。
我想检查这些列表,然后删除相同的项,。
我写了下面的代码,但运行后,应用程序显示错误和崩溃的应用程序!
我的代码:
if (ALLERGIC_LIST.isNotEmpty()) {
ALLERGIC_LIST.forEach { allergic ->
//Added to user list
userLocalList.add(LocalDataModel(allergic.faName.toString(), true, 0, allergic.id!!))
userRecyclerView.adapter!!.notifyDataSetChanged()
//Remove from temp list
dataListTemp.forEach { temp ->
Log.e("AllergicLogs","${allergic.id} - ${temp.id}")
if (allergic.id == temp.id) {
dataListTemp.remove(temp)
}
}
searchList.adapter!!.notifyDataSetChanged()
}
}Logcat中的错误消息:
2022-10-13 08:44:07.617 11990-11990/com.myapp E/AllergicLogs: 1791538835 - 1749914577
2022-10-13 08:44:07.617 11990-11990/com.myapp E/AllergicLogs: 1791538835 - 1762590770
2022-10-13 08:44:07.617 11990-11990/com.myapp E/AllergicLogs: 1791538835 - 1791538835
2022-10-13 08:44:07.617 11990-11990/com.myapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp, PID: 11990
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at com.myapp.AllergicFragment.onViewCreated$lambda-14$lambda-7(AllergicFragment.kt:233)
at com.myapp.AllergicFragment.$r8$lambda$VH4SurM8Hl44Zx-Iy-J2iPtdh8g(AllergicFragment.kt)
at com.myapp.AllergicFragment$$ExternalSyntheticLambda3.onChanged(D8$$SyntheticClass)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:133)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:151)
at androidx.lifecycle.LiveData.setValue(LiveData.java:309)
at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
at androidx.lifecycle.LiveData$1.run(LiveData.java:93)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)我如何修复它和删除相同的项目?
发布于 2022-10-13 05:36:27
dataListTemp.forEach { temp ->
Log.e("AllergicLogs","${allergic.id} - ${temp.id}")
if (allergic.id == temp.id) {
dataListTemp.remove(temp)// Here is the error. You're doing concurrent modification here
dataListTempDuplicate.remove(temp)//Instead delete from duplicate array
}
}发布于 2022-10-13 05:43:22
dataListTemp = dataListTemp.filter { dataItem->
ALLERGIC_LIST.find {it.id == dataItem.id} == null
} 过滤器从lambda中移除所有不返回true的项。find函数将检查过敏列表中是否有带有该id的项,如果没有则返回null。因此,如果find返回一个匹配项,则在筛选器lambda中返回false并跳过该项。如果没有,则从lambda返回true,并将其保存在筛选的列表中。
这将替换整个外部foreach循环。运行时将是O(n^2),但do是原始的。
https://stackoverflow.com/questions/74050855
复制相似问题