2016-05-18 87 views
0

輸入是一個哈希映射返回鍵 - 值列表,例如像如何從散列映射

HashMap<String, String> hashmap = new HashMap<String, String>(); 

for (Map.Entry<String, String> entry : hashmap.entrySet()) { 
      String key = entry.getKey(); 
      Object value = entry.getValue(); 
} 

我想編寫返回類型A類的列表的方法,其中有鍵,值字符串類型的屬性和散列表的鍵值。

如何使它成爲現實,感謝先進。

+0

你的意思是你有一個有2個屬性的類A:String key;字符串值;你必須創建一個這些objescts的列表,同時從hashmap獲取值,對吧? – Arctigor

回答

2
List<A> listOfA= new ArrayList<>(); 
for (Map.Entry<String, String> entry : hashmap.entrySet()) { 
      String key = entry.getKey(); 
      String value = entry.getValue(); 
      A aClass = new A(key, value); 
      listOfA.add(aClass); 
} 
return listOfA; 
+0

當數據已經在Map.Entry中時,爲什麼要複製到類「A」的實例? –

+0

我不知道,但由於OP希望這樣,我只是提供了一個解決方案,但我完全同意你所說的 – Arctigor

3

如果您正在使用的Java 8,你可以做這樣的事情:

List<Entry<String, String>> list = hashmap 
    .entrySet() // Get the set of (key,value) 
    .stream() // Transform to a stream 
    .collect(Collectors.toList()); // Convert to a list. 

如果您需要A類型的元素的列表,你可以適應:

List<A> list = hashmap 
    .entrySet() // Get the set of (key,value) 
    .stream()  // Transform to a stream 
    .map(A::new) // Create objects of type A 
    .collect(Collectors.toList()); // Convert to a list. 

假設您在A中有一個構造函數,如下所示:

A(Map.Entry<String,String> e){ 
    this.key=e.getKey(); 
    this.value=e.getValue(); 
} 

我希望它有幫助。