I want to compare two List<List<String>>
that contain the same elements in any order. They are not equal.
// expectedResult
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
the other is
// result
[
["eat", "tea", "ate"],
["bat"],
["tan", "nat"]
]
What test methods (from which libraries) should I use to compare elements inside **elements without sorting ?**
I tried this unsuccessfully.
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;
assertThat(expectedResult, containsInAnyOrder(result));
The method .containsAll()
works for a Collection not for a Collection of Collection.
Basically I ended up comparing each elements of the first collection, then use .containsAll()
for the nested collection.
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
@Test
public void groupAnagramsTest() {
List<List<String>> expectedResult = Arrays.asList(Arrays.asList("bat"), Arrays.asList("nat", "tan"), Arrays.asList("ate", "eat", "tea"));
List<List<String>> result = Arrays.asList(Arrays.asList("bat"), Arrays.asList("tan", "nat"), Arrays.asList("tea", "eat", "ate"));
// to test the equality without order,
// assert that all elements are contained in the compared list and vice versa
for (int i = 0; i < result.size(); i++) {
Assert.assertTrue(expectedResult.get(i).containsAll(result.get(i)));
Assert.assertTrue(result.get(i).containsAll(expectedResult.get(i)));
}
}
NOTE: the order of the outer List is the same between the two. Otherwise it won't work.