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,971 questions

51,913 answers

573 users

How to shuffle a list in Java

2 Answers

0 votes
import java.util.List;
import java.util.Arrays;
import java.util.Random;

public class MyClass
{
    public static<T> void ShuffleList(List<T> list) {
        Random random = new Random();
 
        for (int i = list.size() - 1; i >= 1; i--) {
            int j = random.nextInt(i + 1);
 
            T obj = list.get(i);
            list.set(i, list.get(j));
            list.set(j, obj);
        }
    }
 
    public static void main(String[] args)
    {
        List<Integer> list = Arrays.asList(0, 1, 2, 3, 4 ,5 ,6 ,7, 8, 9);
 
        ShuffleList(list);
 
        System.out.println(list);
    }
} 
 
 
 
 
/*
run:
 
[2, 7, 8, 1, 0, 9, 3, 4, 5, 6]
 
*/

 



answered Mar 25, 2023 by avibootz
0 votes
import java.util.List;
import java.util.Arrays;
import java.util.Collections;

public class MyClass
{
    public static void main(String[] args)
    {
        List<Integer> list = Arrays.asList(0, 1, 2, 3, 4 ,5 ,6 ,7, 8, 9);
 
        Collections.shuffle(list);
 
        System.out.println(list);
    }
} 
 
 
 
 
/*
run:
 
[6, 1, 5, 9, 0, 8, 2, 4, 3, 7]
 
*/

 



answered Mar 25, 2023 by avibootz

Related questions

2 answers 143 views
143 views asked Nov 8, 2023 by avibootz
2 answers 140 views
140 views asked Oct 30, 2021 by avibootz
1 answer 145 views
145 views asked Mar 29, 2021 by avibootz
1 answer 164 views
164 views asked Mar 28, 2021 by avibootz
1 answer 254 views
254 views asked Mar 15, 2021 by avibootz
1 answer 164 views
1 answer 105 views
105 views asked Oct 18, 2022 by avibootz
...