繁体   English   中英

如何从哈希映射返回键值列表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM