我有一份清单ids。我想过滤我的列表,只保留该列表中与 id 匹配的值。
fun filterHelper(ids: List<Int>, list: List<People>) {
list.filter { ids.contains(it.id) }
}
Run Code Online (Sandbox Code Playgroud)
但这是非常低效的。它本质上是遍历列表 O(n^2)。Kotlin 能让我做得更好吗?
我有一个列表,我想创建一个包含特定 id 的所有值的对象。
val list = listOf(A(id = 1), A(1), A(2), A(3), A(2))
Run Code Online (Sandbox Code Playgroud)
从该列表中,我想制作一个新的类型列表 Container
data class Container(
val id: Long // The id passed into A.
val elementList: List<A> // The elements that contain the ID.
)
Run Code Online (Sandbox Code Playgroud)
如何在不进行 O(n^2) 的情况下以有效的方式执行此操作?
我希望类UploadWorker从类中检索一个值Manager,但该值可能尚未在Manager. 所以我希望类UploadWorker等待该值被设置。
class UploadWorker(appContext: Context, workerParams: WorkerParameters):
Worker(appContext, workerParams) {
override fun doWork(): Result {
Manager.isReady()
return Result.success()
}
}
object Manager {
private lateinit var isReady
fun initialize(context: Context, myData: MyData) {
...
isReady = true
}
suspend fun isReady() {
if(::isReady.isInitialized()
return isReady
else // wait here until initialized
}
}
Run Code Online (Sandbox Code Playgroud)
在其他情况下,如果我能以某种方式suspend或等到我的MyApplication班级打电话initialize()。有任何想法吗?
我有这个类,用于从 Firebase 获取远程配置。
internal object MyConfig {
const val KEY = "test_key"
private var remoteConfig: FirebaseRemoteConfig = FirebaseRemoteConfig.getInstance()
init {
val configSettings = FirebaseRemoteConfigSettings.Builder()
.setMinimumFetchIntervalInSeconds(3600)
.build()
remoteConfig.setConfigSettingsAsync(configSettings)
remoteConfig.fetchAndActivate()
}
fun getKey(): String {
return mRemoteConfig.getString(KEY)
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但如果我在应用程序打开时没有互联网,那么密钥将是"". 当我恢复互联网时,关键仍然是""我调用getKey().
我怎样才能做到这一点,如果键作为 the 返回,""则该值不会存储在remoteConfig?
有没有办法使它必须在 IO 范围内使用协程调用函数?
我想我能做到
suspend fun f() {}
Run Code Online (Sandbox Code Playgroud)
但也许有一个注释?
如果我仍然希望函数被阻塞怎么办?因为在函数内部,我通常进行 db 调用。
我需要id为每个Person对象创建一个唯一的.
public interface Person
{
String getName();
}
public class Chef implements Person
{
String name;
....
// all other instance variables are not unique to this object.
}
public class Waiter implements Person
{
String name;
....
// all other instance variables are not unique to this object.
}
Run Code Online (Sandbox Code Playgroud)
其中的所有其他实例变量Chef不是特定的唯一Chef.我们也不能在Chef类中添加任何额外的变量以使其唯一.这是因为此信息来自后端服务器,我无法修改Chef该类.这是一个分布式系统.
我想创建一个允许我映射此Person对象的整数.我试图创造一个"独特" id.
private int makeId(Person person)
{
int id = …Run Code Online (Sandbox Code Playgroud)