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

后端 未结 5 2073
抹茶落季
抹茶落季 2021-02-06 03:37

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.

5条回答
  •  青春惊慌失措
    2021-02-06 04:23

    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 getQuestionOptionsMap() {
        Map 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 order = new ArrayList<>(map.keySet());
        Collections.shuffle(order);
        Map shuffled = new LinkedHashMap<>();
        for (Integer key : order)
            shuffled.put(key, map.get(key));
        return shuffled;
    }
    

提交回复
热议问题