Best structure for list of key-value (integer, string) to be shuffled

MDT picture MDT · Sep 13, 2013 · Viewed 78.8k times · Source

I need to implement a structure in Java that is a key-value list (of types Integer-String) and I want to shuffle it.

Basically, I would like to do something like that.

    public LinkedHashMap<Integer, String> getQuestionOptionsMap(){

    LinkedHashMap<Integer, String>  shuffle = new LinkedHashMap<Integer, String> ();

    if (answer1 != null)
        shuffle.put(new Integer(1), answer1);
    if (answer2 != null)
        shuffle.put(new Integer(2), answer2);
    if (answer3 != null)
        shuffle.put(new Integer(3), answer3);
    if (answer4 != null) 
        shuffle.put(new Integer(4), answer4);

    Collections.shuffle(shuffle);
    return shuffle;
}

However, HashMap cannot be shuffled.

I could randomly get a key from the hashmap, and then return the linked element, but I'm sure this is not the best solution for my problem.

Is there any better way?

Thanks in advance.

Answer

Konstantin Yovkov picture Konstantin Yovkov · Sep 13, 2013

Create a Pair class, that holds both the Integer and the String and then add multiple Pair objects to a List, which will be shuffled.

public class Pair {
  private Integer integer;

  private String string;

  //accessors
}

Then:

List<Pair> list = new ArrayList<Pair>();
//...add some Pair objects to the list
Collections.shuffle(list);