Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing one element from list according to preference

Tags:

java

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:

  1. If there is an element whose property has value "A", then pick that element.
  2. Else, if there is an element whose property has value "B", then pick that element.
  3. Else, if there is an element whose property has value "C", then pick that element.
  4. Finally if no element has been chosen yet, then throw an exception.

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"?

like image 457
aht Avatar asked Dec 13 '22 22:12

aht


1 Answers

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.

like image 182
Kevin Anderson Avatar answered Feb 11 '23 11:02

Kevin Anderson