# Ensure difference between sets

An endpoint that my application interacts with allows you to specify which fields are returned in the JSON result. My application will then map the JSON to a POJO using Jackson. Quite often I add more fields in one place and forget to add it in the other which results in problems. I wrote a unit test to help make the process easier but I feel like there could be room for improvements.

Here's what I have so far:

private static final String[] POTENTIAL_FIELDS = new String[] { "field1", "field2" };

@Test
public void checkFields() {
// get all constant fields
Set<String> constantFields = Arrays.stream(POTENTIAL_FIELDS)
.map(String::toLowerCase)
.collect(Collectors.toSet());

// get all private fields
Set<String> reflectFields = Arrays.stream(FieldsModel.class.getDeclaredFields())
.filter((field) -> !Modifier.isStatic(field.getModifiers()))
.map(field -> field.getName().toLowerCase())
.collect(Collectors.toSet());

Set<String> symmetricDifference = Sets.symmetricDifference(constantFields, reflectFields);

// check if there's a difference
if (!symmetricDifference.isEmpty()) {
Assert.fail(String.format("Difference: %s\n", String.join(",", symmetricDifference)));
}
}

private static class FieldsModel {
private int field1;
private String field2;
}


The only non-standard imports are FieldsModel which is what the name suggests, and Sets which is from Guava (com.google.coom.collect.Sets). Here is a direct link to the method I used.

• "Here's what I have so far" Does it work like you want it? – Mast Jul 29 at 16:36
• Yes it does, it has the desired effect. I just was wondering if there was a more efficient way to find the disjunctive union than Guava's symmetricDifference or if I did something weird with Assert.fail(...) – Michael Ziluck Jul 29 at 16:37
• Do you know how Sets.symmetricDifference works? Is the algorithm available in literature or how do you suggest we can compare it to other methods? – dfhwze Jul 29 at 18:46
• @dfhwze Just edited my post to provide a direct link to that method. – Michael Ziluck Jul 29 at 18:55
• @dfhwze Edited again to include those – Michael Ziluck Jul 29 at 19:33

1. If you are using only one class there is no need to use ArrayList for POTENTIAL_FIELDS and then after converting it to set. Class will have a unique field name.
• In the comments on my original question, they asked me to add in POTENTIAL_FIELDS so testers didn't need to. In the actual code, it's in a separate class. Also, where do you see an ArrayList? – Michael Ziluck Aug 2 at 12:51