It took a comparison. There are 2 sheets of objects of the same type ( field1 and field2 in the example). The object has 3 string parameters (first name, last name, middle name). In the first object there are records of 3 people with all the fields filled, i.e. It looks like this:

  1. Full name
  2. Yuri Karamazin Aleksandrovich
  3. Victor Sushko G.
  4. Sasha Knyazev Albertovich

And the second object in which records about the same 3 people, but only names are stored:

  1. Name
  2. Yuri
  3. Victor
  4. Sasha

I need to compare only the parameter of the object "name". I'm trying to compare something like this:

 for (FieldOfTest x : field1) { for (FieldOfTest y : field2) { Assert.assertTrue(x.getName().equals(y.getName()), "First value: " + x.getName() + " , second value: " + y.getName()); } } 

The second for scrolls through the full list. How can I compare 1 object from the first list with one object from the second list?

  • And what is the ultimate goal of this comparison? And if you want to compare the first element of field1 only with the first element of field2 , the second - only with the second, etc., then this is done in one cycle. - Regent
  • this is a test. It’s just that the first object is formed by sampling absolutely all the information from the database, therefore the objects are complete, and the second is parsed from the site where only the names are presented. Those. in fact, I need to make sure that the list of names I sent from the site corresponds to the list of names from the database. And yes, in fact, you have correctly indicated that it is necessary to compare only the field "name" of the first object in sheet 1 with the field "name" of the first object in sheet 2; the field "name" of the second object in sheet 1 with the field "name" of the second object in sheet 2, etc. to the end of the sheet. Can this really be simplified? - Ustin

5 answers 5

If you only need to compare elements that are on the same index, then it is enough to use one for , after making sure that the arrays are of equal length:

 public static void main(String[] args) { List<FieldOfTest> field1 = new ArrayList<>(); field1.add(new FieldOfTest("Юрий", "Карамазин Александрович")); field1.add(new FieldOfTest("Виктор", "Сушко Григорьевич")); field1.add(new FieldOfTest("Саша", "Князев Альбертович")); List<FieldOfTest> field2 = new ArrayList<>(); field2.add(new FieldOfTest("Юрий", null)); field2.add(new FieldOfTest("Виктор", null)); field2.add(new FieldOfTest("Саша", null)); System.out.println("Data is correct: " + isCorrectData(field1, field2)); } private static boolean isCorrectData(List<FieldOfTest> field1, List<FieldOfTest> field2) { if (field1.size() != field2.size()) { return false; } boolean isCorrect = true; for (int i = 0; i < field1.size(); i++) { if (!field1.get(i).getName().equals(field2.get(i).getName())) { isCorrect = false; break; } } return isCorrect; } 

Implementation in Java.

  • This is very similar to what is needed. But tell me how you can get around the fact that I have arguments isCorrectData - (ArrayList <FieldOfTest> field1, ArrayList <FieldOfTest> field2). I now do not quite understand. These are sheets of objects, and java writes to me that I cannot take length, why (as I understand it, once I write that there is size, then this is an object, and not an iterative entity like a sheet)? Java proposed to redo the internal if into this construct: if (! Field1.get (i) .getName (). Equals (field2.get (i) .getName ())) {isCorrect = false; break; } - Ustin
  • but what about the original length check? or do I have to push it all into a common for, and there already do checks, create a boolean sheet, insert the result of each iteration there and then check if there are any false s in this list? - Ustin
  • @Ustin pardon, I forgot that you have a List , and not arrays. Now I will correct the code. - Regent
  • @Ustin in List instead of .length is a method .size() , which returns the number of items in this list. And getting the elements happens through the .get(int index) method, as the development environment correctly suggested to you. Code changed. - Regent
  • @Ustin if the lists ( List ) of different lengths, then it makes sense to immediately return false , because the names in them will definitely not be able to completely coincide. It makes no sense to create a whole list of boolean values: you just need to find out if all the names in the lists are the same, and for that, a yes / no answer is enough. - Regent

Well, something like this probably:

 HashMap hashFields=new HashMap<String, FieldOfTest>(); for(FieldOfTest x:field1) hashFields.put(x.getName(), x); //теперь находим в первом списке по именам со второго списка for(FieldOfTest y:field2) //y содержит только имена if(hashFields.get(y)!=null) //bingo! 

PS @VladD ahead.

PPS code for Java

    In any case, you need to look for the entire container. But I would go to a more efficient search data structure. For example, would put the names in a HashSet<string> or a similar data structure in your language, with the search O (1).

    • Well, it's just a simplified model, there are actually many more fields with different types in the object. I simplified to make it easier to understand the essence. I am in this implementation with the sheets will not work to do this? It's just that if I saw sheets of objects, and at least somehow I know, then hashset is a fantasy for me. - Ustin
    • @Ustin: Is the sheet a linear list? No, they are essentially no different from arrays, they only know how to grow. HashSet is not fiction, it is in the standard library of most languages, so it should be easy. - VladD
    • one
      @Ustin: And if there is a more complex object, put it in Dictionary<string, ВашОбъект> , search by key is also O (1). - VladD

    it is necessary to compare only the field "name" of the first object in sheet 1 with the field "name" of the first object in sheet 2; the field "name" of the second object in sheet 1 with the field "name" of the second object in sheet 2, etc. to the end of the sheet

    In Python:

     all(a.name == b.name for a, b in zip(list1, list2)) 

    Full example:

     #!/usr/bin/env python from collections import namedtuple Person = namedtuple('Person', 'name lastname patronymic') list1 = [Person(*s.split()) for s in """\ Юрий Карамазин Александрович Виктор Сушко Григорьевич Саша Князев Альбертович""".split('\n')] list2 = [Person(name, None, None) for name in """ Юрий Виктор Саша""".split()] if all(a.name == b.name for a, b in zip(list1, list2)): print('equal') 

      Option for java . O(n) complexity

       private static class A { String name; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof A)) return false; A a = (A) o; return name.equals(a.name); } @Override public int hashCode() { return name.hashCode(); } } private static class B extends A { String surname; String middleName; } private static boolean isEquals(List<A> firstList, List<B> secondList) { if (firstList.size() != secondList.size()) return false; Set<A> buffer = new HashSet<>(secondList); for (A obj : firstList) if (!buffer.contains(obj)) return false; return true; }