[英]how to return key-value list from a hash map
輸入是一個哈希映射,比如
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 類列表的方法,該列表具有鍵、字符串類型的值屬性以及來自哈希映射的鍵值。
如何讓它成為現實?
如果您使用的是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();
}
我希望它有幫助。
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.