我得到了这种形式的对象的无序列表
class Element {
String property; // has value from the set ("A", "B", "C", "D")
}
没有两个元素具有相同的 property
值。
我想根据如下一组规则选择一个元素并返回其 property
值:
- 如果有一个元素的
property
值为"A"
,则选择该元素。 - 否则,如果有一个元素的
property
值为"B"
,则选择该元素。 - 否则,如果有一个元素的
property
值为"C"
,则选择该元素。 - 最后,如果还没有选择任何元素,则抛出异常。
这是我针对这个问题想出的一个解决方案:
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!");
}
我的问题是:如果将来我想选择 "B"
而不是 “A”
?
最佳答案
而不是将所需的属性值硬编码到 chooseElementProperty
中, 在附加参数中提供它们:
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!");
}
这里我使用了 List<String>
, 但你也可以使用 String[]
甚至是 String...
如果您愿意,可以使用可变参数。
关于java - 根据偏好从列表中选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44610565/