从对象数组中删除重复项

Mut*_*u S -1 android duplicates kotlin android-room

我有一个像下面这样的对象,

class LocationData{
 String time;
 String name;
 String address;
}
Run Code Online (Sandbox Code Playgroud)

对于这个对象,我创建了 getter setter。

通过使用服务,我填写了上述模型并保存到房间数据库中。每当用户打开我的应用程序时,我只是使用 API 将房间数据库数据更新到服务器。现在有时会发生时间重复。如何根据时间从数组中删除对象。时间应该是唯一的。

小智 5

您可以使用扩展功能distinctBy。如果你有一个LocationData对象数组,allLocations它会是

val distinctLocations = allLocations.distinctBy { it.time }
Run Code Online (Sandbox Code Playgroud)

注意distinctLocations将是一个列表;如果您希望它是一个数组,请使用toTypedArray()