Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/main/java/net/datafaker/providers/base/Options.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.datafaker.providers.base;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
Expand Down Expand Up @@ -168,4 +169,19 @@ public <E> E nextElement(E[] array) {
public <E> E nextElement(List<E> list) {
return list.get(faker.random().nextInt(list.size()));
}

/**
* Returns a random element from a collection.
*
* @param collection The collection to take a random element from.
* @param <E> The type of the elements in the collection.
* @return A randomly selected element from the collection.
* @throws IllegalArgumentException if the collection is empty.
* @since 3.0.0
*/
public <E> E nextElement(Collection<E> collection) throws IllegalArgumentException {
return collection.stream()
.skip(faker.random().nextInt(collection.size()))
.findFirst().orElseThrow(() -> new IllegalArgumentException("Collection is empty"));
}
}
17 changes: 17 additions & 0 deletions src/test/java/net/datafaker/providers/base/OptionsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
Expand Down Expand Up @@ -119,6 +121,21 @@ void testNextListElement() {
}
}

@Test
void testNextCollectionElement() {
Collection<Integer> collection = Set.of(1, 2, 3, 5, 8, 13, 21);
for (int i = 1; i < 10; i++) {
assertThat(opt.nextElement(collection)).isIn(collection);
}
}

@Test
void testNextCollectionElementEmpty() {
Collection<Integer> collection = Set.of();
assertThatThrownBy(() -> opt.nextElement(collection))
.isInstanceOf(IllegalArgumentException.class);
}

enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Expand Down