【问题标题】:How to add List of objects in a Map如何在地图中添加对象列表
【发布时间】:2014-11-24 14:59:39
【问题描述】:

我有一个列表,下面定义了 A。

如何在 Map 中添加 Key 为 Long 值,值为 List 的字符串。

Class A
{
Long in;
List<String> out;
}
Map<Long,List<String>>

【问题讨论】:

标签: java collections


【解决方案1】:

创建一个Hashmap 对象,键为Long,值为List。使用put(key,value) 添加项目并使用get 检索它们

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {    
    public static void main(String[] args) {
        Map<Long,List<String>> myMap=new HashMap<Long,List<String>>();
        List<String> myList=new ArrayList<String>();
        myList.add("abc");
        myList.add("xyz");
        myMap.put(new Long(1), myList);
        for(int i=0;i<myList.size();i++)
            System.out.println(myMap.get(new Long(1)).get(i));
    }
}

【讨论】:

    【解决方案2】:

    1.) 使用Key as Longvalue as List&lt;String&gt; 创建HashMap。

    2.) 使用HashMap的put method,如下。

     public static void main(String[] args) {
            Map<Long, List<String>> myMap = new HashMap<Long, List<String>>();
            myMap.put(101L, new ArrayList<String>());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多