Skip to content

Commit 3613428

Browse files
paredpivovarit
authored andcommitted
random element from list guide (eugenp#690)
* random element from list guide * refactor * with removing * refactor + thread optimized index generation * refactor * final review refactor
1 parent 2ef8bc2 commit 3613428

1 file changed

Lines changed: 57 additions & 1 deletion

File tree

‎core-java-8/src/test/java/com/baeldung/RandomListElementTest.java‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,71 @@
33
import org.junit.Test;
44

55
import java.util.Arrays;
6+
import java.util.Collections;
67
import java.util.List;
78
import java.util.Random;
9+
import java.util.concurrent.ThreadLocalRandom;
810

911
public class RandomListElementTest {
1012

1113
@Test
12-
public void givenList_whenRandomNumberChosen_shouldReturnARandomElement() {
14+
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
1315
List<Integer> givenList = Arrays.asList(1, 2, 3);
1416
Random rand = new Random();
17+
1518
givenList.get(rand.nextInt(givenList.size()));
1619
}
20+
21+
@Test
22+
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
23+
List<Integer> givenList = Arrays.asList(1, 2, 3);
24+
25+
givenList.get((int)(Math.random() * givenList.size()));
26+
}
27+
28+
@Test
29+
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() {
30+
Random rand = new Random();
31+
List<String> givenList = Arrays.asList("one", "two", "three", "four");
32+
33+
int numberOfElements = 2;
34+
35+
for (int i = 0; i < numberOfElements; i++) {
36+
int randomIndex = rand.nextInt(givenList.size());
37+
givenList.get(randomIndex);
38+
}
39+
}
40+
41+
@Test
42+
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() {
43+
Random rand = new Random();
44+
List<String> givenList = Arrays.asList("one", "two", "three", "four");
45+
46+
int numberOfElements = 2;
47+
48+
for (int i = 0; i < numberOfElements; i++) {
49+
int randomIndex = rand.nextInt(givenList.size());
50+
givenList.get(randomIndex);
51+
givenList.remove(randomIndex);
52+
}
53+
}
54+
55+
@Test
56+
public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() {
57+
List<Integer> givenList = Arrays.asList(1, 2, 3, 4, 5, 6);
58+
Collections.shuffle(givenList);
59+
60+
int randomSeriesLength = 3;
61+
62+
givenList.subList(0, randomSeriesLength - 1);
63+
}
64+
65+
@Test
66+
public void givenList_whenRandomIndexChosen_shouldReturnElementThreadSafely() {
67+
List<Integer> givenList = Arrays.asList(1, 2, 3, 4, 5, 6);
68+
int randomIndex = ThreadLocalRandom.current().nextInt(10);
69+
70+
givenList.get(randomIndex);
71+
}
72+
1773
}

0 commit comments

Comments
 (0)