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

大城市里の小女人 提交于 2019-12-03 03:10:53

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

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

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
Hashtable<Integer, String>

As an alternative to less convenient and effective List<SomePairClass<Integer, String>>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!