By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,654 Members | 1,517 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,654 IT Pros & Developers. It's quick & easy.

Array List to HashMap

karthickkuchanur
100+
P: 156
Hi,

1.I am having the arraylist which contains string like A,A,B,C,C

2.I need to separe the unique value in to map

3.The output must be like {1=[A, A]},{2=[b]},{3=[C, C]}

4.I tried something hardly but i can't

Expand|Select|Wrap|Line Numbers
  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.Iterator;
  4. import java.util.List;
  5.  
  6.  
  7.   public class Test
  8.   {
  9.     public static void main(String[] args)
  10.     {
  11.       List<String> list = new ArrayList<String>();
  12.       list.add("A");
  13. list.add("A");
  14. list.add("B");
  15.  
  16.       list.add("C");
  17.       list.add("C");
  18.       ArrayList<String> tempList = new ArrayList<String>();
  19.       HashMap<Integer,ArrayList<String>> hashMap = new HashMap<Integer,ArrayList<String>>();
  20.       int count = 1;
  21.       for (Iterator iterator = list.iterator(); iterator.hasNext();)
  22.       {        
  23.         String string = (String) iterator.next();
  24.  
  25.         for (int i = 0; i <list.size(); i++)
  26.         {
  27.           if (!hashMap.isEmpty() )
  28.           {
  29.             tempList = hashMap.get(i);
  30.             if (tempList !=null && tempList.contains(string)) 
  31.             {
  32.               tempList.add(string);
  33.               hashMap.put((Integer)count, tempList);
  34.             }
  35.           } 
  36.           else {
  37.             tempList.add(string);
  38.             hashMap.put((Integer)count, tempList);
  39.           }
  40.         }
  41.         count++;
  42.       }
  43.       System.out.println(hashMap);
  44.     }
  45.  
  46.   }
  47.  
  48.  

Finally the 5 values int the ArrayList need to group by 3 ,i will take the value from the key of hash map .Please help me
Aug 1 '12 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.