0

I have these classes:

Object 1
 String label
 List<Object2>

Object2
 String label
 List<Object3>

Object3
 String label

I want to compare two lists of Object1. This is what I did:

public class Object1 implements Comparator<Object1> {
    @Override
    public int compare(Object1 o1, Object1 o2) {
     int compare = o1.getLabel().compareTo(o2.getLabel());
        if (compare == 0) {
            Iterator<Object2> iterator1 = o1.getObjects2().iterator();
            Iterator<Object2> iterator2 = o2.getObjects2().iterator();
            while (iterator1.hasNext() && iterator2.hasNext() && compare == 0) {
                Object2 t1 = iterator1.next();
                Object2 t2 = iterator2.next();
                compare = t1.getLabel().compareTo(t2.getLabel());
            }
        }
        return compare;
}

And I did the same for Object2.

I sort my list of Object1 by calling it in the code by:

SomeObject.getListOfObject1().stream().sorted();

Is there any other method "cleaner" than this? I feel like I am missing something...

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Anna
  • 839
  • 2
  • 17
  • 33
  • "I sort my list of Object1 by calling it in the code by: `SomeObject.getListOfObject1().stream().sorted();`" that would only sort stream, not source of stream. You need to skip `.stream()` call and sort list directly. – Pshemo Oct 03 '17 at 11:41
  • Hi, First at all, your test can be wrong : if the two list hasn't the same size, your comparaison won't be full (it'll end at the smallest of the two lists) – Tuco Oct 03 '17 at 11:42
  • It seems there should be a helper to lexicographically compare two lists, but apparently not. https://stackoverflow.com/questions/31769122/does-java-have-a-function-that-lexicographically-orders-lists-not-their-element – Thilo Oct 03 '17 at 11:44
  • Ok thanks for the feedback. – Anna Oct 03 '17 at 12:21
  • Possible duplicate of [Java Compare Two Lists](https://stackoverflow.com/questions/2762093/java-compare-two-lists) – RubioRic Oct 03 '17 at 12:22

2 Answers2

0
  1. Firstly, I recommend you to sort the list directly using Collections.sort(..)

  2. Secondly, I'd implement the compare(..) method to all the Object1, Object2 and Object3 each. If you want to create in the future more complex structures using these object, they will be already implemented.

  3. Lastly, implement the equals() and the hashCode() methods.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

one simple way you could go about it is to override the equals() and hash() method of your objects then use the equals() method of the list to compare two lists eg. list1.equals(list2);

danijax
  • 69
  • 5