2013-07-10 57 views
0

我想遍历地图中的几个条目...Java的地图迭代

wizard(),我把4名映射在map,然后发送地图有两个输入cancertest一起被calcuated ...

public int wizard() { 
    Map<String, String> map = new HashMap<String, String>(); 
    //historical data of having cancer given test result... 

    map.put("+cancer", "+test"); 
    map.put("-cancer", "+test"); 
    map.put("-cancer", "-test"); 
    map.put("+cancer", "+test"); 

    String cancer = "+cancer"; 
    String test = "+test"; 

    //send historical data to be calculated... 
    return calculate(cancer, test, map); 
} 

这里,calcuate()遍历地图索引寻找到两个输入cancertest比赛,然后返回的条件概率:

public int calculate(String cancer, String test, Map<String, String> map) { 
    int tests = 0; 
    int both = 0; 

    System.out.println("Cancer: " + cancer + "; Test: " + test); 
    for (int i = 0; i <= map.size(); i++) { 
     if (map.containsValue(test)) { 
      tests++; 
      if (map.containsValue(cancer)) { 
       both++;  
      } 
     } 
    } 
    System.out.println("{Cancer & Tests}: " + both + "; Tests: " + tests); 
    return both/tests; 
} 

输出:

Cancer: +cancer; Test: +test 

{Cancer & Tests}: 0; {Tests}: 3 

P(Cancer|Test): 0 

你可以看到,both++没有增加(又名:{Cancer & Tests}:不应该是0),因此P(Cancer|Test)没有给予正确的答案。

这是为什么?我是否在地图上错误地迭代?

回答

3

为什么你需要一个循环?我不确定你想要达到什么目的。你应该在“关键”中寻找癌症。

应该已经阅读

if (map.containsKey(cancer)) { 
    } 

其他神秘的事情是:

map.put("-cancer", "+test"); 
    map.put("-cancer", "-test"); 

只有第二项将是那里的地图。你用第二个条目覆盖第一个条目。

可能是你可以遍历地图状

for (Map.Entry<String, String> entry : map.entrySet()) { 
     String entry = entry.getKey(), value = entry.getValue(); 
     //Do comparisons. 
     //increment counter 
    } 
3

要遍历在地图上,使用entrySet()

for(Map.Entry<String, String> entry : map.entrySet()) { 
    if(entry.getValue().equals(test)) { 
     tests++; 
     if(entry.getKey().equals(cancer)) { 
      both++; 
     } 
    } 
} 
2

containsValue方法着眼于属于地图(在第二put)内的值,但不是键(第一中put)。以确定是否是在图中,使用containsKey方法。

但是,不仅是你遍历Map不正确,你从一开始误用。一个Map不允许重复键,因为密钥不能映射到多个值。所以,你的第三次和第四次调用put分别覆盖第二个和第一个键。你只有两个条目。

我会创造一个Pair类来保存你的“癌症”,并在同一个对象的“结果”的价值观,并使用Pair为重点,以您的地图(不要忘了覆盖PairequalshashCode,所以Map工作正常)。您可以使用将特定组合映射到其计数的Map<Pair, Integer>。你叫put之前,调用containsKey看是否Pair已经存在,如果是这样,put现有的值加1,要不然就把1的值。然后,在calculate,您可以getPair对象你的计数

要访问这些值,请使用entrySet方法获得Map中条目的Set视图。

+0

好,嗯,是有一些其他的方式做一个关联数组,如:'$ DATA [0] =阵列( “+癌症”,“+测试“);','$ Data [1] = array(” - cancer“,”-test“);'?我只想遍历关联数组的每个部分,并查看这些值是否包含在特定的数组索引处。 – Growler

+0

我已经用可能的解决方案修改了我的答案。 – rgettman

0
map.put("+cancer", "+test"); 
map.put("-cancer", "+test"); 
map.put("-cancer", "-test"); 
map.put("+cancer", "+test"); 

当您添加或"+cancer"两次"-cancer",第二次覆盖的第一个。根据定义,Map只能包含一个给定键的条目。每次使用相同的密钥添加新条目时,都会替换之前的条目。

+0

好的,有没有其他的方法来做一个关联数组,如:'$ Data [0] = array(“+ cancer”,“+ test”);','Data [1] = array(“ - 癌症“,” - 测试“);'?我只想遍历关联数组的每个部分,并查看这些值是否包含在特定的数组索引处。 – Growler

+1

“Map”是一个关联数组。如果您想将_multiple values_与一个键相关联,您需要一个'MultiMap',它不是标准Java集合的一部分,尽管有几种实现可用作开源库。 –