I have a hard coded string that will be used in a URL and I'm wanting to know is what the best way to build this string without having to repeat the words country, or, and, number
? This is a shortened version as there are more countries and numbers that will go into the URL.
String url = "&filter=country='UK' or "
+ "country='FR' or "
+ "country='CA' or "
+ "country='US' and "
+ "number='123' and "
+ "number='789'";
You can use a combination of StringBuilder
and String
formats to build your specific URL parametrization.
Here's an example:
// test data
List<String> countries = Arrays.asList("UK", "FR","CA", "US");
List<String> numbers = Arrays.asList("123", "789");
// these can be compile-time constants
String disjunct = " or ";
String conjunct = " and ";
String countryFormat = "country='%s'";
String numberFormat = "number='%s'";
// result
StringBuilder result = new StringBuilder("&filter=");
// adding countries
for (String country: countries) {
result.append(String.format(countryFormat, country)).append(disjunct);
}
// removing last "or"
result.delete(result.lastIndexOf(disjunct), result.length());
// adding first "and"
result.append(conjunct);
// adding numbers
for (String number: numbers) {
result.append(String.format(numberFormat, number)).append(conjunct);
}
// removing last "and"
result.delete(result.lastIndexOf(conjunct), result.length());
// printing result
System.out.println(result);
Output
&filter=country='UK' or country='FR' or country='CA' or country='US' and number='123' and number='789'