Does the Collection.shuffle () method serve to clutter lists only?

2

I created a set:

Set<Integer> bombo1 = new LinkedHashSet<>();

And I want to mess up the whole. The problem is that I do not know how. I've tried with:

Collections.shuffle(bombo1);

but only serves to sort lists in the List interface. Let's see if they can help me. Thanks !!

    
asked by Cristian Navarro Fernandez 07.03.2018 в 00:56
source

1 answer

2

If you want to use Collections.suffle I understand that you want to do this:

  

Collections.suffle () : method used to randomly permute the   list specified using a default font of   randomness.

To randomly order a Set , you can do it this way, you can add the values of Set to ArrayList and in this way use the method Collections.suffle ()

    //Crea un ArrayList a partir del Set conteniendo los valores originales.
     List<Integer> shuffleList = new ArrayList<Integer>(bombo1);
     //Permuta aleatoriamente la lista.
     Collections.shuffle(shuffleList);    
     //Crea un nuevo Set en donde se almacenarán los datos ordenados aleatoriamente.
     Set<Integer> shuffledSet = new LinkedHashSet<Integer>();
     //Agrega los valores ordenados alatoriamente a un nuevo Set.
     shuffledSet.addAll(shuffleMe); 

In this way shuffledSet will contain the randomly sorted values.

I add a example online :

    // LinkedHashSet de elementos tipo Integer.
     Set<Integer> lhset = new LinkedHashSet<Integer>();
     // Agrega elementos.
     lhset.add(12);
     lhset.add(1);
     lhset.add(57);
     lhset.add(0);
     lhset.add(9);
     lhset.add(34);
     System.out.println("Set original: " + lhset);


     //Crea un ArrayList a partir del Set conteniendo los valores originales.
     List<Integer> shuffleMe = new ArrayList<Integer>(lhset);
     //Permuta aleatoriamente la lista.
     Collections.shuffle(shuffleMe);    
     //Crea un nuevo Set en donde se almacenarán los datos ordenados aleatoriamente.
     Set<Integer> shuffledSet = new LinkedHashSet<Integer>();
     //Agrega los valores ordenados alatoriamente a un nuevo Set.
     shuffledSet.addAll(shuffleMe); 

     System.out.println("Set desordenado : " +  shuffledSet);

Exit:

Set original: [12, 1, 57, 0, 9, 34]
Set desordenado : [0, 1, 34, 12, 9, 57]
    
answered by 07.03.2018 в 02:12