0

I have followed this answer to check if two lists of different type are equal based on same fields.

Here the working function :

private <T, U> boolean compareLists(List<T> list1, List<U> list2, BiPredicate<T, U> predicate) {

    return list1.size() == list2.size() &&
                list1.stream().allMatch(itme1 -> list2.stream().anyMatch(item2 -> predicate.test(itme1, item2)));
}

But when I called it that way

compareLists(list1, list2,
        (item1, item2) ->
                item1.someField11.equals(item1.someField21) &&  item1.someField12.equals(item1.someField22)
)

I got Cannot resolve symbol 'someField11' (same for the other fields)

I had to declare it this way bellow to make it work

BiPredicate<Foo1, Foo2> biPredicate = (item1, item2) ->
                    item1.someField11.equals(item1.someField21) &&  item1.someField12.equals(item1.someField22)

So how to make it work without extra local variable biPredicate ?

  • UPDATE SOLUTION

list1 was type of Set not List so I changed the function signature to Collection

Hayi
  • 6,972
  • 26
  • 80
  • 139
  • 1
    If the compiler cannot infer types correctly, that is because the context does not enable it to. I can only guess that `list1` and `list2` aren't declared with the correct generic arguments. Please add how you declare them. – ernest_k Apr 29 '20 at 05:21
  • @ernest_k yeah it was the same problem but not with the generic, i was calling the function with `Set` not `List` – Hayi Apr 29 '20 at 05:26

1 Answers1

1

Seems like type inference is falling flat. You can specify the argument types yourself, like this:

compareLists(list1, list2,
        (Foo1 item1, Foo2 item2) ->
                item1.someField11.equals(item1.someField21) &&  item1.someField12.equals(item1.someField22)
)
  • I just figure out the problem, `list1` was type of `Set` not `List` so I changed the function signature to `Collection` – Hayi Apr 29 '20 at 05:19
  • but thanks for the trick with specifying the argument types myself i didn't know that i we can do it this way – Hayi Apr 29 '20 at 05:23