Skip to content

Instantly share code, notes, and snippets.

@4sskick
Last active August 15, 2019 07:21
Show Gist options
  • Save 4sskick/ec3f88768812d71cfc35b8a838a4befb to your computer and use it in GitHub Desktop.
Save 4sskick/ec3f88768812d71cfc35b8a838a4befb to your computer and use it in GitHub Desktop.
this methods useful whenever you build dummy data using model
private static <E> List<E> pickNRandomElements(List<E> list, int n, Random r) {
int length = list.size();
if (length < n) return null;
//don't need to shuffle the whole list
for (int i = length - 1; i >= length - n; --i) {
Collections.swap(list, i, r.nextInt(i + 1));
}
return list.subList(length - n, length);
}
public static <E> List<E> pickNRandomElements(List<E> list, int n) {
return pickNRandomElements(list, n, new Random());
}
/**
* how to use
*/
new ArrayList<dataType>( yourClass.pickNRandomElements( youListData, sizeOfNData ) )
//for realmList implementation
new RealmList<dataType>( yourClass.pickNRandomElements( youListData, sizeOfNData ) ).toArray( new String[yourListData.size()] )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment