Home >Java >javaTutorial >How to Read a Text File into an ArrayList in Java?

How to Read a Text File into an ArrayList in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 05:59:09681browse

How to Read a Text File into an ArrayList in Java?

Java: Read a Text File into an Array List

Introduction

Reading a text file into an array list in Java is a common programming task. This article demonstrates how to achieve this, covering techniques that leverage the Files, String, Integer, and List classes.

Reading the File

To read the file, use the Files#readAllLines() method to obtain a list of its lines. Each line represents a row in the text file.

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));

Splitting the Lines

Since the values in the file are separated by spaces, use the String#split() method to break each line into individual values:

for (String line : lines) {
    String[] values = line.split("\s+");
}

Converting Strings to Integers

As the values in the text file are integers, convert them to Integer objects using Integer#valueOf():

for (String value : values) {
    Integer i = Integer.valueOf(value);
}

Adding to Array List

Create an array list and add the converted integers to it using the List#add() method:

List<Integer> numbers = new ArrayList<>();
numbers.add(i);

Combining the Steps

Combining these steps, you can read the file and populate the array list in one go:

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    for (String value : line.split("\s+")) {
        Integer i = Integer.valueOf(value);
        numbers.add(i);
    }
}

Java 8 Stream API

In Java 8, you can simplify the process using the Stream API:

List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
    .map(line -> line.split("\s+")).flatMap(Arrays::stream)
    .map(Integer::valueOf)
    .collect(Collectors.toList());

The above is the detailed content of How to Read a Text File into an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn