I'm given an unordered list of objects of this form
class Element {
String property; // has value from the set ("A", "B", "C", "D")
}
where no two elements have the same property
value.
I want to choose one element according to a set of rules like the following and return its property
value:
property
has value "A"
, then pick that element.property
has value "B"
, then pick that element.property
has value "C"
, then pick that element.This is one solution I've come up with for this problem:
String chooseElementProperty(List<Element> elements) {
// Iterates the list and creates a set of all the property values.
// example: [{property: 'A'}, {property: 'B'}] -> {'A', 'B'}
Set<String> propertyValues = pluckPropertyValues(elements);
if (propertyValues.contains("A"))
return "A";
if (propertyValues.contains("B"))
return "B";
if (propertyValues.contains("C"))
return "C";
throw new IllegalArgumentException("Invalid input!");
}
My question is: What is a better/cleaner way to do this that makes this method more extensible where it's easier to change my preference if in the future I want to choose "B"
over "A"
?
Rather than having the desired property values hard-coded into chooseElementProperty
, provide them in an additional argument:
String chooseElementProperty(List<Element> elements, List<String> prefs) {
// Iterates the list and creates a set of all the property values.
// example: [{property: 'A'}, {property: 'B'}] -> {'A', 'B'}
Set<String> propertyValues = pluckPropertyValues(elements);
for (String s: prefs) {
if (propertyValues.contains(s))
return s;
}
throw new IllegalArgumentException("Invalid input!");
}
Here I've used a List<String>
, but you could also use a String[]
or even a String...
varargs if you prefer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With