2013-07-10 42 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; 
}