Java 8 here. I have a method checkDupeKeys
that will take three different SortedMap
instances as its arguments and needs to verify that no two SortedMap
instances have identical keys. My best attempt thus far:
private void checkDupeKeys(SortedMap<String, Fizz> fizzes, SortedMap<String, Buzz> buzzes,
SortedMap<String, Foobar> foobars) {}
List<String> keyNames = new ArrayList<>();
keyNames.addAll(fizzes.keySet().stream().collect(Collectors.toList()));
keyNames.addAll(buzzes.keySet().stream().collect(Collectors.toList()));
keyNames.addAll(foobars.keySet().stream().collect(Collectors.toList()));
if(keyNames.size() > keyNames.stream().collect(Collectors.toSet()).size()) {
throw new IllegalArgumentException("Duplicate key names are not allowed.");
}
}
I believe this works, however there might very well be a better way of going about it (efficiency, etc.).
My main concern is that this method doesn't allow me to identify which key names are duplicates. I'd ideally like the exception message to be:
Duplicate key names are not allowed. You have the following duplicate key names: (1) fizzes["derp"] and buzzes["derp"]. (2) fizzes["flim"] and foobars["flim"]. (3) buzzes["flam"] and foobars["flam"].
How can I modify my (non-static) checkDupeKeys
method to throw an exception that meets this criteria? That is, how do I get access to which keys inside the streams are duplicates of each other. I'm sure I could do this the hard way using older Java collections APIs, but efficiency and leveraging Java 8 APIs are important to me in this solution.