john
john

Reputation: 65

Text file to 2 different arraylist

I have a text file (statecapitals.txt) that has "State - Capital" like this:

Alaska - Juneau
Arizona - Phoenix
Arkansas - Little Rock
California - Sacramento
Colorado - Denver
Connecticut - Hartford
Delaware - Dover
Florida - Tallahassee

How can i get the first field into an arraylist and the second in another arraylist(I cannot modify the text file)?

Upvotes: 1

Views: 48

Answers (2)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22234

Assuming you have managed to iterate over each line of the file and added each line as a String in a List<String> lines;

You can now create 2 new List with each String like this :

List<String> states = new ArrayList<>();
List<String> capitals = new ArrayList<>();

for (String line : lines) {
    String[] words = line.split(" - ");
    if (words.length == 2) {
        states.add(words[0]);
        capitals.add(words[1]);
    }
}

Upvotes: 0

janos
janos

Reputation: 124666

You can split the lines using .split(" - "). See the JavaDoc.

For example:

    String content = "Alaska - Juneau\n" +
            "Arizona - Phoenix\n" +
            "Arkansas - Little Rock\n" +
            "California - Sacramento\n" +
            "Colorado - Denver\n" +
            "Connecticut - Hartford\n" +
            "Delaware - Dover\n" +
            "Florida - Tallahassee\n";

    Scanner scanner = new Scanner(content);

    List<String> states = new ArrayList<>();
    List<String> capitals = new ArrayList<>();

    while (scanner.hasNextLine()) {
        String[] parts = scanner.nextLine().split(" - ");
        states.add(parts[0]);
        capitals.add(parts[1]);
    }

    System.out.println(states);
    System.out.println(capitals);

Upvotes: 2

Related Questions