Shuffling Elements of Unordered Collections in Java
Unordered Collections in java does not provide any order i.e. the elements cannot be accessed using specific indexing or ordering as we could in the case of ordered collections such as List. Sets and Maps are examples of unordered collections.
In java, we cannot shuffle unordered collections directly using Collections.shuffle() method as it expects a List as a parameter.
For shuffling the elements,
- We have to first store the elements of the unordered collection inside a List, and then we can shuffle it using Collections.shuffle() method.
1) Shuffling Elements of a Set
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Set<Integer> st = new HashSet<>();
st.add( 91 );
st.add( 0 );
st.add( 55 );
st.add( 10 );
st.add( 9 );
st.add( 9 );
System.out.print( "The Set before shuffling: " );
for ( int i : st)
System.out.print(i + " " );
System.out.println();
List<Integer> list = new ArrayList<>(st);
Collections.shuffle(list);
System.out.print( "The List (containing elements of the Set) after shuffling: " );
for ( int i : list)
System.out.print(i + " " );
}
}
|
Output
The Set before shuffling: 0 55 9 10 91
The List (containing elements of the Set) after shuffling: 55 0 91 10 9
2) Shuffling Elements of a Map
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Map<Integer, String> mp
= new HashMap<Integer, String>();
mp.put( 1 , "Geeks" );
mp.put( 2 , "for" );
mp.put( 3 , "Geeks" );
mp.put( 4 , "is" );
mp.put( 5 , "love" );
System.out.println( "The Map before shuffling: " );
for (Map.Entry<Integer, String> entry :mp.entrySet())
System.out.println(entry.getKey() + " "
+ entry.getValue());
System.out.println();
List<Map.Entry<Integer, String> > list
= new ArrayList<>(mp.entrySet());
Collections.shuffle(list);
System.out.println( "The List (containing the elements of the Map)"
+ " After shuffing: " );
for (Map.Entry<Integer, String> entry : list)
System.out.println(entry.getKey() + " "
+ entry.getValue());
System.out.println();
}
}
|
Output
The Map before shuffling:
1 Geeks
2 for
3 Geeks
4 is
5 love
The List (containing the elements of the Map) After shuffing:
2 for
5 love
4 is
3 Geeks
1 Geeks
Last Updated :
29 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...