0

I have two lists of different objects

class objectA {
String aId;
String aTitle;
String aUrl;
...
}
class objectB {
String bId;
String bTitle;
String bUrl;
...
}

List<ObjectA> aObjectList;
List<ObjectB> bObjectList;

I need to verify that these two lists have equal values for Id and Title fields. The way I see is to create Map<String, String> from two lists and then compare them.

List<Map<String, String>> aObjectMapList = aObjectList.stream()...
List<Map<String, String>> bObjectMapList = bObjectList.stream()...

But maybe assertj has an appropriate approach to solve my issue?

I would be grateful for any solution to my issue via stream or assertj or somehow else.

2
  • Are the lists guaranteed to be the same size? Commented Sep 2, 2021 at 10:15
  • @MCEmperor yes, they will have the equal size from the beginning. Commented Sep 2, 2021 at 10:34

2 Answers 2

2

I'd make a string id+title for each object, in 2 lists. Then compare the 2 lists

List<String> aList = aObjectList.stream()
   .map(a -> a.getaId() + a.getaTitle())
   .collect(Collectors.toList());
List<String> bList = bObjectList.stream()
   .map(b -> b.getbId() + b.getbTitle())
   .collect(Collectors.toList());

boolean sameElements = aList.size() == bList.size() && 
                       aList.containsAll(bList) && 
                       bList.containsAll(aList);
Sign up to request clarification or add additional context in comments.

Comments

1

It could make sense to merge id / title into a single String, remap the input lists into List<String> and then use AssertJ hasSameElements to compare the new lists:

assertThat(
    aObjectList.stream()
               .map(a -> String.join(":", a.aId, a.aTitle))
               .collect(Collectors.toList())
).hasSameElementsAs(
    bObjectList.stream()
               .map(b -> String.join(":", b.bId, b.bTitle))
               .collect(Collectors.toList())

);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.