简体   繁体   中英

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)?

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);

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]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM