If you are using Java 8 onward, something like this would work, provided that there are >= 5 elements in the list:
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.
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. Something like this in your DAO:
@Query("SELECT * FROM person ORDER BY RANDOM() LIMIT 5")
public List<Person> getFiveRandomPersons();
Typically an observer would observe
a subject; 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 might give you some idea on the usage of observe()
.