DMQ95
DMQ95

Reputation: 1521

Retrieve random object from ArrayList

The method below is the method I am using to populate my array. However I wish to return a random deals_informationobject from my ArrayList of type Deals_Information but am not quite sure how.

    public void populateArray() {

    databaseReference.child("FruitDeals").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Iterable<DataSnapshot> children = dataSnapshot.getChildren();
            final ArrayList<Deals_Information> myArray = new ArrayList<>();

            for (DataSnapshot child : children) {
                Deals_Information deals_information = child.getValue(Deals_Information.class);
                myArray.add(deals_information);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

Upvotes: 0

Views: 593

Answers (2)

Lavaman65
Lavaman65

Reputation: 863

Because ArrayLists have a get() function, the way to do this is to first generate a random number by using the math.random() function, and then use the get() function of your ArrayList to call the object at that randomly generated index.

Upvotes: 0

Dreando
Dreando

Reputation: 589

Use Random to get a random int from the range of 0 and the size-1 of your collection.

Since Java 1.7, the recommended Random implementation is ThreadLocalRandom.

private int randomInt(final int from, final int to) {
    return ThreadLocalRandom.current().nextInt(from, to);
}

Upvotes: 1

Related Questions