Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to create a random sublist from a list in Java

2 Answers

0 votes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RandomSublistExample {
    public static void main(String[] args) {
        // Original list
        List<Integer> lst = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            lst.add(i);
        }

        // Shuffle the list
        Collections.shuffle(lst);

        // Define the size of the sublist
        int sublistSize = 5;

        // Extract the random sublist
        List<Integer> randomSublist = lst.subList(0, sublistSize);

        // Print the random sublist
        System.out.println("Random Sublist: " + randomSublist);
    }
}

 
 
/*
run:
 
Random Sublist: [4, 8, 2, 9, 6]
 
*/

 



answered Jun 20, 2025 by avibootz
0 votes
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class RandomSublistExample {
    public static void main(String[] args) {
        // Original list
        List<Integer> lst = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            lst.add(i);
        }

        // Define the size of the sublist
        int sublistSize = 5;

        // Select random elements without shuffling
        Set<Integer> selectedIndices = new HashSet<>();
        Random random = new Random();
        while (selectedIndices.size() < sublistSize) {
            selectedIndices.add(random.nextInt(lst.size()));
        }

        List<Integer> randomSublist = new ArrayList<>();
        for (int index : selectedIndices) {
            randomSublist.add(lst.get(index));
        }

        // Print the random sublist
        System.out.println("Random Sublist: " + randomSublist);
    }
}

 
 
/*
run:
 
Random Sublist: [2, 5, 6, 7, 9]
 
*/

 



answered Jun 20, 2025 by avibootz
...