2016-05-18 88 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(); 
} 

我希望它有帮助。