2014-01-08 36 views
0

我試着去找出正確的地圖或列表使用...隨機選擇Java值映射

我需要將值添加到列表或地圖和檢索,然後randomly..ie

喜歡的東西

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" 

然後傳遞索引變量的值...

爲指數1

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

任何想法歡迎...

回答

0

試試這個

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

的想法是改變鍵集中在一個數組,然後獲得從數組隨機密鑰,然後得到的,從價值地圖

0
  1. 通常情況下,鍵/值對假定有一個映射,但在您的案例中名稱可能有重複。因此,您最好使用一個列表(對:名稱/ from,例如Pair)來存儲數據(除非我對重複的假設是錯誤的)。
  2. ,因爲你需要的數據使用ArrayList
  3. 從集合中提取隨機值是一個完全獨立的問題有隨機訪問:

    • 你想/允許重複或不?
    • 你需要生成一個隨機的子集(集合)還是有一個函數給你一個列表中的下一個隨機值(可能帶有重複)?

假設你想從列表中的數據的隨機子集使用谷歌Permutations類。假設你想從列表中隨機選擇一個下一個值(帶有重複),例如, Math.random()*datalist.size(),並將其轉換(整數)爲整數以得到元素的索引,然後可以使用datalist.get(index)來提取元素。