简体   繁体   English

如何从 Room 数据库中接收 5 个随机对象并将它们添加到新的 ArrayList

[英]How to recieve 5 random Objects from Room database and add them to a new ArrayList

  1. I have method personViewModel.getNoobs();我有方法personViewModel.getNoobs(); which returns List<Person> from Room database;从 Room 数据库返回List<Person>
  2. I have new ArrayList<Person> currentNoobList;我有新的ArrayList<Person> currentNoobList; in my Activity.在我的活动中。

I need to take 5 random Persons from database and add them to currentNoobList in onCreate() .我需要从数据库中随机抽取 5 个 Persons 并将它们添加到onCreate()中的currentNoobList中。

As far as I know, I need to use .observe in order to get random Objects from that List<Person> which I get using method getNoobs() ;据我所知,我需要使用.observe来从使用方法getNoobs()获得的List<Person>中获取随机对象; but I cannot understand how to write this code correctly.但我无法理解如何正确编写此代码。 Could you help?你能帮忙吗?

Thanks!谢谢!

If you are using Java 8 onward, Something like this would work, provided that there >= 5 elements in the list:如果您使用 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()))));

If you are unable to use Java 8, this answer could come in handy.如果您无法使用 Java 8,这个答案可能会派上用场。

Given that you are using a Room Database, You could add an annotated method stub in your DAO interface and make appropriate changes such that you can directly get your results via your database.鉴于您使用的是房间数据库,您可以在 DAO 接口中添加带注释的方法存根并进行适当的更改,以便您可以直接通过数据库获取结果。 Something like this in your DAO:在你的 DAO 中是这样的:

@Query("SELECT * FROM person ORDER BY RANDOM() LIMIT 5")
    public List<Person> getFiveRandomPersons();

Typically a observer would observe a subject;通常,观察者会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.鉴于没有太多信息,我相信您正在使用Livedata ,因为您在 Room Database 的上下文中提到.observe This documentation and this codelab might give you some idea on the usage of observe()文档和本codelab可能会让您对observe()的使用有所了解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM