2017-05-25 51 views
-2

在Java中,我實現這一點:如何從地圖得到具體值<字符串,列表<String >>

Map<String, List<String >> mdaps = new HashMap<String, List<String >>(); 

我想以顯示包含「拿下」這樣的單詞列表:

Scored [Profile] 
Scored [Applicability] 

但是如何在entry.getkey()中搜索?

,因爲它不工作:if(entry.getKey().contrains("Scored"))

這裏是我的代碼: EDIT1

Map<String, List<String >> mdaps = new HashMap<String, List<String >>(); 

      List<String > List1 = new ArrayList<String>(); 
      List<String > List2 = new ArrayList<String>(); 
      List<String > List3 = new ArrayList<String>(); 

      List1.add("Profile"); 
      List2.add("Applicability"); 
      List3.add("Level 1"); 

     mdaps.put("(Scored)", List1); 
     mdaps.put("(Scored)", List2); 
     mdaps.put("Not Scored", List3); 

     for(Map.Entry<String, List<String>> entry : mdaps.entrySet()){ 

       if(entry.getKey().contains("(Scored)")) // not Working 
      System.out.println(entry.getKey()+" "+ entry.getValue()); 
     } 
    } 

DemoProgramm

在此先感謝。

+7

'contrains' - >'contains' ?? – OldCurmudgeon

+2

嘗試entry.getKey()。equals(「Scored」)。你有兩個相同的鍵添加項目。但它會替換第一項 –

+1

1.代碼中包含另一個錯誤:當您使用同一個鍵將它插入到'mdaps'中時,您正在用'List2'覆蓋'List1'。 2.在命名變量時使用Java約定:List1 - > list1等。3.嘗試爲變量提供更有意義的名稱。 – alfasin

回答

0

你過了通過將再次使用相同的密鑰寫入鍵值「(計)」。所以List1不會在sysout中顯示。你不應該爲不同的值使用相同的密鑰。 HashMap使用key的hasCode()來存儲值,而具有相同值的String將具有相同的hascode。它認爲它是一樣的。因此寫了價值。

1

entry.getKey()將返回一個集合,它將包含您的密鑰,以便它將始終返回true。

for (Map.Entry<String, List<String>> entry : mdaps.entrySet()) { 

      if (entry.getKey().equals("Scored")) // not Working 
       System.out.println(entry.getKey() + " " + entry.getValue()); 
     } 
+0

感謝你的回答,但是如果該行包含單詞「(Scored)」或者不是? – Michael1

+0

什麼你想要你的鑰匙滿足你可以放。 –

0

的解決辦法是更換contrains由包含:

for (Map.Entry<String, List<String>> entry : mdaps.entrySet()) { 

      if (entry.getKey().contains("(Scored)")) 
       System.out.println(entry.getKey() + " " + entry.getValue()); 
     } 
相關問題