리스트에서 무작위로 요소를 가져오는 방법을 소개합니다.
Random.nextInt(bound)는 bound 미만의 양수를 리턴합니다. bound는 포함되지 않습니다.
아래와 같이 리스트 길이를 nextInt()의 인자로 전달하여, 랜덤 Index를 계산해서 리스트에서 가져올 수 있습니다.
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class Example {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Hello", "World", "Java", "Python", "Kotlin", "C++");
Random random = new Random();
int randomIndex = random.nextInt(myList.size());
System.out.println(myList.get(randomIndex));
randomIndex = random.nextInt(myList.size());
System.out.println(myList.get(randomIndex));
randomIndex = random.nextInt(myList.size());
System.out.println(myList.get(randomIndex));
}
}
Output:
World
Hello
Kotlin
Collections.shuffle()는 인자로 전달된 리스트의 순서를 무작위로 변경합니다. 순서가 변경되었기 때문에 Index 0부터 가져오면 무작위의 요소를 가져올 수 있습니다.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Hello", "World", "Java", "Python", "Kotlin", "C++");
Collections.shuffle(myList);
System.out.println(myList);
}
}
Output:
[Kotlin, Java, World, Python, Hello, C++]
Collections.shuffle()는 기존 리스트의 순서를 변경하는데, 기존 리스트의 순서 변경을 원하지 않을 때는 아래와 같이 리스트를 복사하고 복사된 리스트에 대해서 shuffle()을 수행해야 합니다.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Hello", "World", "Java", "Python", "Kotlin", "C++");
List<String> copy = new ArrayList<>(myList);
Collections.shuffle(copy);
System.out.println("myList: " + myList);
System.out.println("copy: " + copy);
}
}
Output:
myList: [Hello, World, Java, Python, Kotlin, C++]
copy: [Kotlin, World, Hello, C++, Python, Java]
[자바] 리스트 역순 순회 (0) | 2023.04.12 |
---|---|
[싱글톤] 싱글톤 패턴 구현 (0) | 2023.04.12 |
[스트림] 특정 조건으로 헤쉬맵 필터링 (0) | 2023.04.12 |
[스트림] reduce 사용법 및 예제 (0) | 2023.04.12 |
[람다식] 람다식 사용법 및 예제 (0) | 2023.04.12 |
댓글 영역