2014-02-22 32 views
1

我是Java的新手,請耐心等待。從列表中拉入口<String>嵌套在HashMap中

我有一個列表的HashMap。

static Map<Integer, List<String>> contactList = new HashMap<Integer, List<String>>(); 

我遍歷,HashMap中的每一個條目,並使用它顯示:

for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) { 
      System.out.println(entry.getKey() + " - " + entry.getValue()); 
     } 

現在,entry.getValue()是存儲我的名單,但我只想第一,這些列表的第二個和第三個條目。我相信我需要在迭代之前將列表分配給它自己的對象,但我似乎無法從HashMap中提取列表。

輸出必須顯示HashMap的每個條目,包括它的鍵值,但只顯示列表的前3項。

回答

5

只需打印subList無需修改數據:

System.out.println(entry.getKey() + " - " + entry.getValue().subList(0, 3)); 

假設,你的列表中有2組以上的元素,否則你可以使用Math.min(3, entry.getValue().size())(如在評論中提到的),以避免IndexOutOfBoundsException

因此,

System.out.println(entry.getKey() + " - " + entry.getValue().subList(0, Math.min(3, entry.getValue().size()))); 
+0

這個答案比我的更簡潔和優雅(我顯然沒有足夠的考慮)。儘管你想用'Math.min(3,entry.getValue()。size())'做子表,如果它更短。 – Gorkk

+0

非常好的答案,保持它! – Keerthivasan

+0

@Gorkk謝謝我根據OP的要求做出了一個假設,但是您的建議會使解決方案准確 – PopoFibo

0

怎麼是這樣的:

String result = ""; 
List<String> strings = entry.getValue(); 
for (int i = 0; i < strings.size(); i++) 
{ 
    result += strings.get(i); 
} 
2

你可以不喜歡這樣。我已經做了詳細說明,以幫助您更好地理解。此代碼可以製作得更短

Map<Integer, List<String>> contactList = new HashMap<Integer, List<String>>(); 
    for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) { 
     Integer integer = entry.getKey(); 
     List<String> list = entry.getValue(); 
     //first item 
     String first = list.get(0); 
     //second item 
     String second = list.get(1); 
     //third item 
     String third = list.get(2); 
    } 

希望它有幫助!

+0

做到這一點,這將產生,如果列表我短則3 – zibi

+0

由於OP提到有三個我所提供的答案例外其中的物品 – Keerthivasan

+0

謝謝,這正是我所尋找的。它給了我需要的對象分配和輸出的粒度類型。 – vbiqvitovs

1

下面的代碼應該給你你想要的。

for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) { 
    List<String> values = entry.getValue(); 
    StringBuilder builder = new StringBuilder(entry.getKey()).append(" - "); 
    // here I assume the values list is never null, and we pick at most the first 3 entries 
    builder.append("[") 
    for (int i = 0; i < Math.min(3, values.size()); i++) { 
     if (i > 0) builder.append(", "); 
     builder.append(values.get(i)); 
    } 
    builder.append("["); 
    System.out.println(builder.toString()); 
} 

它是什麼,在地圖的每個條目:

  1. 創造與價值的局部變量(一個List<String>
  2. 創建StringBuilder建設上的輸入
  3. 輸出
  4. 在構建輸出的同時迭代前3項(或更少,如果列表更短)
  5. 在構建器中輸出字符串

如果您仔細考慮,確實有更好的方法來做到這一點,這只是您問題的快速基本解決方案。

0

我的朋友,你可以通過

Map<Integer, List<String>> contactList = new HashMap<Integer, List<String>>(); 
      for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) { 
       List<String> list = entry.getValue(); 
       String firstItem = list.get(0); 
       String secondItem = list.get(1); 
       String thirdItem = list.get(2); 

      }