Is there a better way to do this so I don't have to have 50 ".add()"s in there? Like a comma separated list or something (like JavaScript arrays).
private static final Set<String> validStates = new HashSet<String>();
validStates.add("AL");
validStates.add("AK");
validStates.add("AZ");
validStates.add("AR");
validStates.add("CA");
validStates.add("CO");
validStates.add("CT");
validStates.add("DE");
validStates.add("DC");
validStates.add("FL");
validStates.add("GA");
validStates.add("HI");
validStates.add("ID");
validStates.add("IL");
validStates.add("IN");
validStates.add("IA");
validStates.add("KS");
validStates.add("KY");
validStates.add("LA");
validStates.add("ME");
validStates.add("MD");
validStates.add("MA");
validStates.add("MI");
validStates.add("MN");
validStates.add("MS");
validStates.add("MO");
validStates.add("MT");
validStates.add("NE");
validStates.add("NV");
validStates.add("NH");
validStates.add("NJ");
validStates.add("NM");
validStates.add("NY");
validStates.add("NC");
validStates.add("ND");
validStates.add("OH");
validStates.add("OK");
validStates.add("OR");
validStates.add("PA");
validStates.add("RI");
validStates.add("SC");
validStates.add("SD");
validStates.add("TN");
validStates.add("TX");
validStates.add("UT");
validStates.add("VT");
validStates.add("VA");
validStates.add("WA");
validStates.add("WV");
validStates.add("WI");
validStates.add("WY");
Something like:
validStates.add("AL", "AK", "...");
The HashSet
has a constructor taking a Collection
. The Arrays#asList()
takes arguments as varargs and returns a List
(which is a Collection
). So, you could do it as follows:
validStates = new HashSet<String>(Arrays.asList("AL", "AK", ".."));
It makes however more sense to have them in some properties file or in a DB which you load by one or two lines of code so that you don't need to hardcode them all in Java.
If you were on Java 8+, you could just use Stream#of()
.
validStates = Stream.of("AK", "AL", "..").collect(Collectors.toSet());
If you fancy using the excellent Google Guava library, you can use:
Set<String> validStates = Sets.newHashSet("AL", "AK", "...");
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