如何从 Room 数据库接收 5 个随机对象并将它们添加到新的 ArrayList
How to recieve 5 random Objects from Room database and add them to a new ArrayList
- 我有方法
personViewModel.getNoobs();
,其中 returns List<Person>
来自 Room 数据库;
- 我的 Activity 里有新的
ArrayList<Person> currentNoobList;
。
我需要从数据库中随机抽取 5 个人物并将它们添加到 onCreate()
中的 currentNoobList
。
据我所知,我需要使用 .observe
才能从我使用方法 getNoobs()
获得的 List<Person>
中获取随机对象;
但我不明白如何正确编写这段代码。你能帮忙吗?
谢谢!
如果您使用的是 Java 8 以后,只要列表中有 >= 5 个元素,这样的方法就可以了:
List<Person> personList = personViewModel.getNoobs();
Random random = new Random();
IntStream.range(0,5).forEach(val ->
currentNoobList.add(personList.remove(random.nextInt(personList.size()))));
如果你无法使用Java8,这个answer可以派上用场。
鉴于您正在使用 Room 数据库,您可以在 DAO 接口中添加一个带注释的方法存根并进行适当的更改,以便您可以直接通过数据库获取结果。在你的 DAO 中是这样的:
@Query("SELECT * FROM person ORDER BY RANDOM() LIMIT 5")
public List<Person> getFiveRandomPersons();
通常观察者会observe
一个主题; Checkout Observer Pattern. Given there isn't much information, I believe you are using Livedata
, since you mentioned .observe
in context with the Room Database. This documentation and this codelab 可能会让您对 observe()
的用法有所了解
- 我有方法
personViewModel.getNoobs();
,其中 returnsList<Person>
来自 Room 数据库; - 我的 Activity 里有新的
ArrayList<Person> currentNoobList;
。
我需要从数据库中随机抽取 5 个人物并将它们添加到 onCreate()
中的 currentNoobList
。
据我所知,我需要使用 .observe
才能从我使用方法 getNoobs()
获得的 List<Person>
中获取随机对象;
但我不明白如何正确编写这段代码。你能帮忙吗?
谢谢!
如果您使用的是 Java 8 以后,只要列表中有 >= 5 个元素,这样的方法就可以了:
List<Person> personList = personViewModel.getNoobs();
Random random = new Random();
IntStream.range(0,5).forEach(val ->
currentNoobList.add(personList.remove(random.nextInt(personList.size()))));
如果你无法使用Java8,这个answer可以派上用场。
鉴于您正在使用 Room 数据库,您可以在 DAO 接口中添加一个带注释的方法存根并进行适当的更改,以便您可以直接通过数据库获取结果。在你的 DAO 中是这样的:
@Query("SELECT * FROM person ORDER BY RANDOM() LIMIT 5")
public List<Person> getFiveRandomPersons();
通常观察者会observe
一个主题; Checkout Observer Pattern. Given there isn't much information, I believe you are using Livedata
, since you mentioned .observe
in context with the Room Database. This documentation and this codelab 可能会让您对 observe()