Compare two lists contaning different objects

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pjerald
    New Member
    • Oct 2007
    • 77

    Compare two lists contaning different objects

    Dear all,

    I have a list object, which contains list objects. This list objects contains objects of different type like String, long, BigDecimal and so on..

    for eg.,
    if we print it in console it will be like this,

    list object is :
    [
    [jerald,26,"#32 chennai", 43.0098],
    [Roses,25,"#06 kanya kumari", 13.00108]
    ]

    this example object has two records and should be compared with similar two record list object. comparision should be done by its data type. For eg., BigDecimal objects , we shoud take care of comparing like this,

    bigdecimal1.com pareTo(bigdecim al2)

    I have an array of datatype {String, int,String,BigD ecimal} to compare. please any one help.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    You should've made a little class for every 'row' in your List. That little class should implement the Comparable interface; the rest would be easy then. Your approach is too Fortanesque.

    kind regards,

    Jos

    ps. and get rid of those arrays as well.

    Comment

    • pjerald
      New Member
      • Oct 2007
      • 77

      #3
      Thank you JosAH,

      I am trying to do this. I have written some code. I will reply when i am finished.

      Regards
      jerald

      Comment

      • pjerald
        New Member
        • Oct 2007
        • 77

        #4
        Dear josAH,

        Here is my code,


        Code:
        package test;
        
        import java.math.BigDecimal;
        import java.util.ArrayList;
        import java.util.List;
        
        public class ExpenseComparator {
            public static void main(String[] args) throws Exception
            {
                List<Object> expected = new ArrayList();
                List<Object> received = new ArrayList();
        
                List<Object> exp1 = new ArrayList();
                List<Object> exp2 = new ArrayList();
                List<Object> rec1 = new ArrayList();
                List<Object> rec2 = new ArrayList();
        
                exp1.add(Long.parseLong("100"));
                exp1.add(new BigDecimal("100.009"));
                exp1.add("32, cross cut road. Chennai.");
        
                exp2.add(Long.parseLong("100"));
                exp2.add(new BigDecimal("100.00"));
                exp2.add("32, cross cut road. Chennai.");
        
                expected.add(exp1);
                expected.add(exp2);
        
                rec1.add(Long.parseLong("100"));
                rec1.add(new BigDecimal("100.00000"));
                rec1.add("32, cross cut road. Chennai.");
        
                rec2.add(Long.parseLong("100"));
                rec2.add(new BigDecimal("100.009"));
                rec2.add("32, cross cut road. Chennai.");
        
                received.add(rec1);
                received.add(rec2);
                
                int a = compareLists(expected, received);
                if(a == 0)
                {
                    System.out.println("Both the lists are equal.");
                }
            }
        
        
            public static int compareLists(List expected, List received) throws Exception
            {
                if(expected.size() != received.size())
                {
                    throw new Exception("Records size missmatch.");
                }
                int flag = 0;
                for(int i=0;i<expected.size();i++) // loop through records.
                {
                    List expList = (List)expected.get(i);
                    CompareRecords tc = new CompareRecords(expList);
                    List recList = null;
                    for(int j=0;j<received.size();j++)
                    {
                        recList = (List) received.get(j);
                        int c = tc.compareTo(recList);
                        {
                            if(c == 0)
                            {
                                received.remove(j);
                                expected.remove(i);
                                flag = 1;
                                break;
                            }
                        }
                    }
                    if(flag == 0)
                    {
                    throw new Exception("Excepted record : "+expList + " is not matched with any records.");
                    }
                }
                return 0;
            }
        }
        class CompareRecords implements Comparable
        {
            List fList = null;
            public CompareRecords(List l)
            {
                fList = l;
            }
            public int compareTo(List list) throws Exception {
                if(fList.size() != list.size())
                {
                    throw new Exception("Columns size missmatch");
                    //return -1;
                }
                int flag = 0;
                for(int i = 0;i<fList.size();i++)
                {
                    Object fo = fList.get(i);
                    Object o = list.get(i);
                    if(o instanceof String)
                    {
                        String fs = (String)fo;
                        String s = (String)o;
                        if(fs.equals(s))
                        {
                            continue;
                        }
                        flag = 1;
                    }
                    else if(o instanceof Long)
                    {
                        Long fl = (Long)fo;
                        Long l = (Long)o;
                        if(fl.equals(l))
                        {
                            continue;
                        }
                        flag = 1;
                    }
                    else if(o instanceof BigDecimal)
                    {
                        BigDecimal fbd = (BigDecimal)fo;
                        BigDecimal bd = (BigDecimal)o;
                        if(bd.compareTo(fbd) == 0)
                        {
                            continue;
                        }
                        flag = 1;
                    }
                }
                if(flag == 1)
                {
                    return 1;
                }
                return 0;
            }
        
            public int compareTo(Object o) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        
        }
        I have some problem with this code. I cannot able to identify which expected column value is not get matched with the exact value in received column value ..

        Any comments please.

        Regards
        Jerald

        Comment

        • pjerald
          New Member
          • Oct 2007
          • 77

          #5
          So here is my entire code.....


          I am comparing two csv files taking care of their data types..


          Code:
          package test;
          
          import java.io.FileInputStream;
          import java.io.FileNotFoundException;
          import java.io.IOException;
          import java.math.BigDecimal;
          import java.util.ArrayList;
          import java.util.List;
          import com.csvreader.CsvReader;
          import java.io.BufferedReader;
          import java.io.InputStreamReader;
          
          public class ExpenseComparator {
              public static void main(String[] args) throws Exception
              {
                  String[] dataType = {"String", "Long", "String", "BigDecimal"};
                  List l1 = getListFromFile("/home/pjerald/test1.xml",dataType);
                  List l2 = getListFromFile("/home/pjerald/test2.xml",dataType);
                  int b = compareLists(l1, l2);
                  if(b == 0)
                  {
                      System.out.println("Both the lists are equal.");
                  }
          
              }
          
          
              public static int compareLists(List expected, List received) throws Exception
              {
                  if(expected.size() != received.size())
                  {
                      throw new Exception("Records size missmatch.");
                  }
                  int flag = 0;
                  for(int i=0;i<expected.size();i++) // loop through records.
                  {
                      List expList = (List)expected.get(i);
                      CompareRecords tc = new CompareRecords(expList);
                      List recList = null;
                      boolean matched = false;
                      for(int j=0;j<received.size();j++)
                      {
                          recList = (List) received.get(j);
                          int c = tc.compareTo(recList);
                          {
                              if(c == 0)
                              {
                                  received.remove(j);
                                  expected.remove(i);
                                  matched = true;
                                  break;
                              }
                              
                          }
                      }
                      if(matched)
                      {
                          continue;
                      }
                      
                          throw new Exception("Excepted record : "+expList + " is not matched with any records.");
                      
                  }
                  return 0;
              }
          
              private static List getListFromFile(String fileName, String[] dataType) throws FileNotFoundException, IOException, Exception
              {
                  CsvReader reader = new CsvReader(new BufferedReader(new InputStreamReader(new FileInputStream(fileName))),',');
                  List<List> list = new ArrayList();
          		if (!reader.readHeaders())
          		{
          			throw new Exception("cannot read headers");
          		}
                  String[] headers = reader.getHeaders();
                  int count = -1;
          		while (reader.readRecord())
          		{
          			List sb = new ArrayList();
          			for (int i = 0; i < headers.length; i++)
          			{
                          count++;
          				String str = reader.get(headers[i]);
          				if (str == null || str.trim().length() == 0)
          				{
          					sb.add(",");
          					continue;
          				}
          				str = str.trim();
                          if(dataType[i].equals("Long"))
                          {
                              Long l = Long.parseLong(str);
                              sb.add(l);
                          }
                          else if(dataType[i].equals("BigDecimal"))
                          {
                              BigDecimal bd = new BigDecimal(str);
                              sb.add(bd);
                          }
                          else
                          {
                              sb.add(str);
                          }
          			}
          			list.add(sb);
                      count = -1;
          		}
          		return list;
          
              }
          }
          class CompareRecords implements Comparable
          {
              List fList = null;
              public CompareRecords(List l)
              {
                  fList = l;
              }
              public int compareTo(List list) throws Exception {
                  if(fList.size() != list.size())
                  {
                      throw new Exception("Columns size missmatch");
                      //return -1;
                  }
                  int flag = 0;
                  for(int i = 0;i<fList.size();i++)
                  {
                      Object fo = fList.get(i);
                      Object o = list.get(i);
                      if(o instanceof String)
                      {
                          String fs = (String)fo;
                          String s = (String)o;
                          if(fs.equals(s))
                          {
                              continue;
                          }
                          flag = 1;
                          break;
                      }
                      else if(o instanceof Long)
                      {
                          Long fl = (Long)fo;
                          Long l = (Long)o;
                          if(fl.equals(l))
                          {
                              continue;
                          }
                          flag = 1;
                          break;
                      }
                      else if(o instanceof BigDecimal)
                      {
                          BigDecimal fbd = (BigDecimal)fo;
                          BigDecimal bd = (BigDecimal)o;
                          if(bd.compareTo(fbd) == 0)
                          {
                              continue;
                          }
                          flag = 1;
                          break;
                      }
                  }
                  return flag;
              }
          
              public int compareTo(Object o) {
                  throw new UnsupportedOperationException("Not supported yet.");
              }
          
          }
          But i cannot able to find which column of the record miss matched.

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            That is not what I expected: a row (e.g. from a database table) represents an entity, a class, say a Person. Every row from that table makes up an object from the Person class. A table would simply be a list of Persons:

            Code:
            List<Person> table= new List<Person>();
            You can add and remove Person objects to/from this list/table. If you want to compare two Person objects for equality you have to implement the equals() and hashCode() methods in the Person class. The List interface itself will help you to do all sorts of clever things with a bunch of Persons but you do have to write such a class; another list of (unrelated) little objects won't make it.

            kind regards,

            Jos

            Comment

            • pjerald
              New Member
              • Oct 2007
              • 77

              #7
              Thanks for the reply.

              My understanding is this ...

              1) Make objects(Say person) from each and every record.
              2) Person class should implement equals and hashcode methods...
              3) Then easily compare each and every (Person objects) records for equality.

              is am i wright ?

              Thanks and Regards
              Jerald.

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                Originally posted by pjerald
                is am i wright ?
                Yep, that's basically it; that way you're hiding the details where those Person objects came from, i.e. you just have to deal with those Person objects.

                kind regards,

                Jos

                Comment

                • pjerald
                  New Member
                  • Oct 2007
                  • 77

                  #9
                  Thank you josAH.

                  I have done the code. Used constructors to make my objects(records from list)

                  works well. Thanks a lot for your replies.

                  regards
                  jerald

                  Comment

                  Working...