如何在java中将列表转换为map

时间:2016-01-09 03:44:53

标签: java

我有arrayList

List<String> li= new ArrayList<String>() ;
li.add("a");
li.add("b");

我想将ArrayList转换为HashMap,就像这样

HashMap<String, List<String>> s= new HashMap<String,List<String>>();

请帮我转换为HashMap

3 个答案:

答案 0 :(得分:3)

You need to look at this List<Item> list; Map<Key,Item> map = new HashMap<Key,Item>(); for (Item i : list) map.put(i.getKey(),i);

答案 1 :(得分:0)

public static void main(String [] args){

    String name;
          int  count=0; 
 List<String> li= new ArrayList<String>() ;
    li.add("a");
    li.add("d");
    li.add("b");
    li.add("e");
    Iterator i1 = li.iterator();
    while(i1.hasNext())
            {
        name = (String)i1.next();
        System.out.println(name);
            }

    HashMap <Integer,String> hm = new HashMap<Integer,String>();
    for(String i : li)
    {
    hm.put(count++,i);
    }
    System.out.println("after converting list to map ");
    System.out.println(hm);
}

答案 2 :(得分:0)

  final List<String> originalList = Arrays.asList("a","b");
    //JAVA 8
    //Always initialize maps/collections with their Interface
    final Map<Integer, String> mapFromListJavaEight =
            IntStream.range(0,originalList.size())
            .mapToObj(index -> index)
            .collect(Collectors.toMap(Function.identity(),
                    originalList::get));
    // JAVA < 8 & JAVA >= 5
    final Map<Integer, String> mapFromListJavaSeven =
            new HashMap<>();
    for(int i = 0; i < originalList.size(); i++){
        mapFromListJavaSeven.put(i,originalList.get(i));
    }