-4

I have arrayList

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

I want to convert to ArrayList to HashMap Like this

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

Please help me how to convert to HashMap

PM 77-1
  • 12,933
  • 21
  • 68
  • 111

3 Answers3

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);

Community
  • 1
  • 1
Rahul Bhawar
  • 450
  • 7
  • 17
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);
}
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));
    }
dmitryvinn
  • 392
  • 3
  • 9