I would like to shuffle values in an HashMap. I have following type of HashMap
Map<Integer,ArrayList<String> > trainDataSet = new HashMap<Integer, ArrayList<String>>();
I would like to shuffle the values in the Map. How would i do it?
Following is my attempt:
collections.shuffle(trainDataSet.values());
Got an error:
Values cannot be cast to java.util.List
Yes this make sense, because my values are in Arraylist not in List. Would it be possible to shuffle collections of arraylist?
EDIT
If i have following order::
key1 [aa,bb,cd]
key2 [xx,xy,sfr]
Into something like
key1 [xx,xy,sfr]
key2 [aa,bb,cd]
You actually want to randomly reassociate keys and values. Here's an example how that can be achieved:
final Map<String, Object> x = new HashMap<String, Object>();
x.put("x", 1); x.put("y", 2); x.put("z", 3); x.put("w", 4);
System.out.println(x);
final List<Object> vs = new ArrayList<Object>(x.values());
Collections.shuffle(vs);
System.out.println(vs);
final Iterator<Object> vIter = vs.iterator();
for (String k : x.keySet()) x.put(k, vIter.next());
System.out.println(x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With