1

I have array lists of cities defined by state abbreviations.

static List<String> AL = Arrays.asList("ABBEVILLE","ADAMSVILLE",.....
static List<String> AK = Arrays.asList("ADAK","AKHIOK",......

The same thing happens to the array no matter which one is called. How do I pass a string of 'AL' and access the array list AL? I currently use a case statement... But its a lot of code for all 50 and I want to trim it down a bit..

 case "AL":
   for(int index = 0; index < AL.size(); index++){.....}
 case "AK":
   for(int index = 0; index < AK.size(); index++){.....}

Id rather something like this:

for(int index = 0; index < state_abbreviation.size(){
  System.out.println(state_abbreviation[index]);

1 Answer 1

3

You could store every List<String> in a Map and use the state abbreviation as the map's key.

import java.util.*;

class Test {
    public static void main(String[] args) {
        Map<String, List<String>> states = new HashMap<String, List<String>>();
        List<String> al = Arrays.asList("ABBEVILLE", "ADAMSVILLE", "...");
        List<String> ak = Arrays.asList("ADAK", "AKHIOK", "...");
        states.put("AL", al);
        states.put("AK", ak);
        System.out.println(states.get("AL").get(1)); // ADAMSVILLE
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This does not really cut down on the amount of code and misses my for loops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.