2013-07-10 60 views
0

我試圖遍歷關聯數組並從中總結每個組合的多少實例有(用於確定的A條件概率給出B爪哇替代PHP索引數組

例如,在PHP我可以遍歷索引數組$數據[I]給定的輸入(A, ~B),並獲得2

$Data[0] = array("A", "~B"); 
$Data[1] = array("~A", "B"); 
$Data[2] = array("A", "~B"); 
$Data[3] = array("A", "B"); 

我試圖在Java中與maps複製此一結果,但僅映射允許每個值的唯一關鍵。 ..因此,以下將無法正常工作,因爲密鑰A我被用於三個條目。

map.put("A", "~B"); 
map.put("~A", "B"); 
map.put("A", "~B"); 
map.put("A", "B"); 

有什麼我可以用的嗎?

謝謝!

+0

它看起來像你的PHP數據結構更準確地對應於一個Java'名單<地圖>'。 –

回答

1

可以使用Map<T,List<U>>(在你的情況下,它是Map<String,List<String>>),也可以使用一些圖書館使用Multimap<String,String>如番石榴(它或Apache公地版本 - MultiMap

0

如果結構的迭代是你的主要目標,List<ConditionResult>似乎是您的情況下最合適的選擇,其中ConditionResult在下面給出。

如果保持組合數是唯一目標,那麼Map<ConditionResult,Integer>也可以很好地工作。

public class ConditionResult 
{ 
    // Assuming strings for the data types, 
    // but an enum might be more appropriate. 
    private String condition; 
    private String result; 

    public ConditionResult(String condition, String result) 
    { 
     this.condition = condition; 
     this.result = result; 
    } 

    public String getCondition() { return condition; } 
    public String getResult() { return result; } 

    public boolean equals(Object object) 
    { 
     if (this == object) return true; 
     if (object == null) return false; 
     if (getClass() != object.getClass()) return false; 
     ConditionResult other = (ConditionResult) object; 
     if (condition == null) 
     { 
      if (other.condition != null) return false; 
     } else if (!condition.equals(other.condition)) return false; 
     if (result == null) 
     { 
      if (other.result != null) return false; 
     } else if (!result.equals(other.result)) return false; 

     return true; 
    } 

    // Need to implement hashCode as well, for equals consistency... 

} 


迭代和計數可以做的:

/** 
* Count the instances of condition to result in the supplied results list 
*/ 
public int countInstances(List<ConditionResult> results, String condition, String result) 
{ 
    int count = 0; 
    ConditionResult match = new ConditionResult(condition,result); 
    for (ConditionResult result : results) 
    { 
     if (match.equals(result)) count++; 
    } 

    return count; 
}