0

Im trying to find out the correct Map or List to use...

I need to add values to a list or map and retrieve then randomly..ie

Something like

Map<String, String>map

index 1 of map (or list) = "John", "John is from some country"
index 2 of map (or list) = "Mary", "Mary is from some country"
index 3 of map (or list) = "Paul", "Paul is from some country"

and then pass the values of the index to variable...

The result for index 1

String name = "John"
String from = "John is from some country"

Any ideas welcome...

user3024760
  • 176
  • 2
  • 13

2 Answers2

0

Try this

 public String randomMap(){
   Map<String,String> test=new TreeMap<String, String>();
   Object[] arraySet=test.keySet().toArray();
   Random randomGenerator = new Random();
   long range = (long) 1- (long) arraySet.length;

   long fraction = (long) (range * randomGenerator.nextDouble());
   int randomNumber = (int) (fraction + 1);
   String setToGet=(String)arraySet[Math.abs(randomNumber)] ;
   String x=test.get(setToGet);
   return (setToGet+x);
}

The idea is to change the keyset in an array then get a random key from the array and then get the value of that from the map

ishimwe
  • 1,216
  • 12
  • 13
0
  1. Normally key/value pairs assume a map, but in your case names are likely to have duplicates. So you are better off using a list (of pairs: name/from, e.g. of type Pair) to store data (unless my assumption about duplications is wrong).
  2. As you need to have random access to data use ArrayList
  3. Extracting random values from a collection is a completely independent problem:

    • do you want/allow duplications or not?
    • do you need to generate a random subset (collection) or to have a function that gives you a next random value from the list (possibly with duplications)?

Assuming you want a random subset of data from the list use Google Permutations class. Assuming you want a random next value from the list (with duplications) use e.g. Math.random()*datalist.size() and convert it (down) to integer to get and index of an element, which then can be extracted using datalist.get(index).

Oleg Sklyar
  • 9,834
  • 6
  • 39
  • 62