10 Replies Latest reply: Jan 11, 2007 1:18 PM by 796365 RSS

    Comparing HashMap to a List

    807607
      I am comparing the entries in a HashMap to the entries in a List. I want to get:
      1. the entries that match,
      2. the entries that are in the List, but not in the HashMap
      3. the entries that are in the Hashmap, but not in the List
       for (Iterator iter = theMap.entrySet().iterator(); iter.hasNext();)
       {
           Map.Entry entry = (Map.Entry)iter.next();
           String key = (String)entry.getKey();
           String value = (String)entry.getValue();
            boolean invalid = true;
      
            for (int i = 0; i < theList.size(); i++)
            {
                    AccountsList accountList= (AccountsList ) theList.get(i);
                    String accountNumber = accountList.getAccountNumber();
      
                   if (key.equals(accountNumber))
                   {
                       System.out.println("VALID");
                       invalid = false;
                   }
            }
            if (invalid)
            {
                  System.out.println("INVALID");
            }
      }
      for (int i = 0; i < theList.size(); i++)
      {
           AccountsList accountList= (AccountsList ) theList.get(i);
           String accountNumber = accountList.getAccountNumber();
           boolean missing = true;
      
           for (Iterator iter = theMap.entrySet().iterator(); iter.hasNext();)
           {
                Map.Entry entry = (Map.Entry)iter.next();
                String key = (String)entry.getKey();
                String value = (String)entry.getValue();
      
                if (theMap.containsKey(accountNumber)
               {
                     missing = false;
                }
           }
           if (missing)
           {
                System.out.println("MISSING");
           }
      }
       
      The code above almost works. Is there a more efficient or easier way to compare a Hashmap to a List and get the 3 criteria I listed above?

      Any help would be greatly appreciated.
        • 1. Re: Comparing HashMap to a List
          807607
          This algorithm works, but it has N^2 complexity. Here is my recommendation:

          You are looking to A-B and B-A where A is the keySet in the map and B is the set of accountNumbers of the accounts in the list. You have one set readily available in the map; construct the set and then use either Set.removeAll(Collection) or some hand made algorithm.
          • 2. Re: Comparing HashMap to a List
            796365
            hemalpandya beat me to the post, but here's a program that illustrates the process. You are matching between the list entries and the map key, ignoring the map value - so that's what this program does:
            import java.util.*;
            
            public class XXXX
            {
                public static void main(String[] args)
                {
                    // a test list
                    List list = Arrays.asList(new Integer(1), new Integer(2));
                    
                    // create a Set from your list
                    Set listSet = new HashSet(list);
                    
                    // a test Map
                    Map map = new HashMap();
                    map.put(new Integer(2), "two");
                    map.put(new Integer(3), "three");
                    
                    // create a Set from your map keys
                    Set mapSet = map.keySet();
                    
                    // create the set that is common to both list and map 
                    Set intersection = new HashSet(listSet);
                    intersection.retainAll(mapSet);
                    
                    // create the set with unmatched list entries
                    Set inList = new HashSet(listSet);
                    inList.removeAll(mapSet);
                    
                    // create the set with unmatched map entries
                    Set inMap = new HashSet(mapSet);
                    inMap.removeAll(listSet);
                    
                    System.out.println(intersection); // prints 2
                    System.out.println(inList); // prints 1
                    System.out.println(inMap); // prints 3
                }
            }
            • 3. Re: Comparing HashMap to a List
              796254
              I'd prefer using the API that already exists in the java.util.Collection interface, like this:
              package cruft;
              
              import java.util.Arrays;
              import java.util.HashMap;
              import java.util.Map;
              import java.util.Set;
              import java.util.List;
              import java.util.ArrayList;
              import java.util.HashSet;
              
              /**
               * Created by IntelliJ IDEA.
               * Date: Jan 10, 2007
               * Time: 10:05:36 PM
               */
              public class HashAndListMatcher
              {
                 public static void main(String[] args)
                 {
                    String [] x = { "a", "b", "d", "f", "h", };
                    String [] y = { "b", "c", "e", "f", "j", };
              
                    Map<String, String> map = new HashMap<String, String>();
                    for (int i = 0; i < y.length; i++)
                    {
                       map.put(y, x[i]);
              }

              Set<String> keys = new HashSet<String>(map.keySet());
              boolean hasChanged = keys.retainAll(Arrays.asList(x));
              System.out.println("in both : " + keys);

              List<String> inListButNotMapKeys = new ArrayList<String>(Arrays.asList(x));
              hasChanged = inListButNotMapKeys.removeAll(map.keySet());
              System.out.println("in list but not map: " + inListButNotMapKeys);

              Set<String> inMapButNotList = new HashSet<String>(map.keySet());
              hasChanged = inMapButNotList.removeAll(Arrays.asList(x));
              System.out.println("in map but not list: " + inMapButNotList);
              }
              }


              It's cleaner than your code, IMO.

              %
              • 4. Re: Comparing HashMap to a List
                807607
                duffymo, if you dont mind me asking, what is the "cruft" package, lol?
                • 5. Re: Comparing HashMap to a List
                  807607
                  Thanks all for the responses.

                  I tested hemal and ChuckBings solution (and awarded the Dukes)before anyone else responded .

                  They worked!

                  again, thanks!
                  • 6. Re: Comparing HashMap to a List
                    807607
                    hemalpandya beat me to the post, but here's a program
                    that illustrates the process.
                    Only by a few minutes and because I did not give code example.
                    • 7. Re: Comparing HashMap to a List
                      807607
                      hemalpandya beat me to the post, but here's a program
                      that illustrates the process.
                      Only by a few minutes and because I did not give code example.
                      • 8. Re: Comparing HashMap to a List
                        796254
                        duffymo, if you dont mind me asking, what is the "cruft" package, lol?
                        Hi TP,

                        I have an IntelliJ project set up where I do little development bits like this one for forum questions. I call the package "cruft" because the classes that I write there tend to have little value and should be deleted once the thread is satisfied.

                        %
                        • 9. Re: Comparing HashMap to a List
                          807607
                          In the first code snippet posted above, what if you are comparing two list with different columns of information:

                          list 1
                          ------------------
                          1/7/2007 100566 NN


                          list 2
                          ------------------
                          OUTAGE Y 100566


                          and all I want to get is the account numbers that are matches, not in list 1 but in list 2, and not in list 2 but in list 2?

                          So I have two disparate lists and I just want to compare a similar column in each list.
                          • 10. Re: Comparing HashMap to a List
                            796365
                            Lists do not contain independent fields. If you have information that consists of multiple fields in a List then it is a kluge and should not have been created,

                            If you have that, and can't make the changes to correctly store the data, then you'll have to read the list element and then parse the element into fields using your own custom code.

                            The comparison can be done as we have shown, making the appropriate substitutions for the data compared.