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

92,401

Solution 1

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);

Solution 2

You can keep the Map. The Map is designed to be looked up by key so I suggest you have a list of shuffled keys.

public Map<Integer, String> getQuestionOptionsMap() {
    Map<Integer, String> map = new HashMap<>();
    String[] answers = {null, answer1, answer2, answer3, answer4};
    for (int i = 1; i < answers.length; i++)
        if (answers[i] != null)
            map.put(i, answers[i]);
    List<Integer> order = new ArrayList<>(map.keySet());
    Collections.shuffle(order);
    Map<Integer, String> shuffled = new LinkedHashMap<>();
    for (Integer key : order)
        shuffled.put(key, map.get(key));
    return shuffled;
}

Solution 3

You could keep a separate List of the keyvalues, shuffle that and use it to access the HashMap.

List<Integer> keys = new ArrayList<Integer>(map.keySet());
Collections.shuffle(keys);
for(Integer i : keys)
    map.get(i);     // Gets the values in the shuffled order
Share:
92,401
MDT
Author by

MDT

Updated on July 05, 2020

Comments

  • MDT
    MDT almost 4 years

    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.

  • Kayaman
    Kayaman over 10 years
    Then you won't get HashMap's O(1) lookup though.
  • MDT
    MDT over 10 years
    Yes that's what I wrote at the end of my question, but I wasn't sure was the best option. Thanks.
  • MDT
    MDT over 10 years
    Thanks, I chose this solution, implementing my Pair class as a class inside my main Class.
  • olinox14
    olinox14 almost 5 years
    Maybe a few explanations would be useful?