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);
Answer from Konstantin Yovkov on Stack OverflowCreate 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;
}
When you call put on the map of type Map <Integer,String>, you will get the String returned. So when you do this:
new HashMap<Integer,String>().put(songID, songList.get(i).name);
it will return a String
and when you try to assign it to a map
Map<Integer,String> map
compiler throws an error,
Type mismatch: cannot convert from String to Map
Here is the signature of put method form javadocs:
public V put(K key,
V value)
you need to break down the this complex problematic statement:
Map<Integer,String> map = new HashMap<Integer,String>().put(songID, songList.get(i).name);
to something like:
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(songID, songList.get(i).name);
The answer on this thread: Java HashMap associative multi dimensional array can not create or add elements
has an example of how to do this.
Use the Map<K, V> interface, and the HashMap<K, V> class for example. Or see the "All Known Subinterfaces" section in the Map<K, V> interface description for more implementations.
http://download.oracle.com/javase/6/docs/api/java/util/Map.html
Java has Hashtable and HashMap
See Differences between HashMap and Hashtable?
You can simply do:
Iterator<String> it = list.iterator();
while(it.hasNext()) {
map.put(it.next(), it.next());
}
This will be more efficient than using the get(index) method (in case the list implementation does not allow random access)
Here's a relatively neat way:
var map = IntStream.range(0, list.size() / 2).boxed()
.collect(Collectors.toMap(i -> list.get(i * 2), i -> list.get(i * 2 + 1)));