【问题标题】:how to return key-value list from a hash map如何从哈希映射中返回键值列表
【发布时间】:2016-05-18 08:59:19
【问题描述】:

输入是一个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 类型列表的方法,它有键、值属性和字符串类型,以及来自 hashmap 的键值。

如何实现?

【问题讨论】:

  • 你的意思是你有一个类A,它有两个属性:字符串键;字符串值;你必须在从哈希图中获取值的同时创建这些对象的列表,对吧?

标签: java hashmap key-value


【解决方案1】:

如果您使用的是 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();
}

希望对你有帮助。

【讨论】:

    【解决方案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;
    

    【讨论】:

    • 当数据已经在Map.Entry 中时,为什么要复制到A 类的实例?
    • 我不知道,但既然 OP 想要这样,我只是提供了一个解决方案,尽管我完全同意你所说的
    猜你喜欢
    • 2011-09-29
    • 2021-06-11
    • 2011-09-30
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2015-10-27
    相关资源
    最近更新 更多