My requirement: I have an interface that shall only contain entries such as public final static short SOME_CONST = whatever
. The catch: the short constants need to be unique. And in when there are duplicates, I am mainly interested in having the SOME_CONST_A, SOME_CONST_B, ... names causing the conflict.
I wrote the below test to test that via reflection. It works, but I find it clunky and not very elegant:
@Test
public void testIdsAreUnique() {
Map<Short, List<String>> fieldNamesById = new LinkedHashMap<>();
Arrays.stream(InterfaceWithIds.class.getDeclaredFields())
.filter(f -> f.getClass().equals(Short.class))
.forEach((f) -> {
Short key = null;
String name = null;
try {
key = f.getShort(null);
name = f.getName();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
fieldNamesById.computeIfAbsent(key, x -> new ArrayList<>()).add(name);
});
assertThat(fieldNamesById.entrySet().stream().filter(e -> e.getValue().size() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)), is(Collections.emptyMap()));
}
Is there a way to avoid that intermediate local map instance?
( bonus question: is there a nicer way to shorten the lambda that fills the map with key/value pairs? )