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

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

Barbara Streisand
Release: 2024-12-13 19:40:13
Original
848 people have browsed it

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

How to Read a Text File into an Array List in Java

Reading data from a text file into an array list can be accomplished in Java through a series of steps:

  1. Get file contents as a list of strings: Using Files#readAllLines() returns all lines of the text file as a List.
  2. Split each line into parts: Split each line using String#split() based on whitespace ("s ").
  3. Convert each part to an integer: Parse the split parts into integers with Integer#valueOf().
  4. Add integers to an array list: Utilize List#add() to incorporate each integer into an array list.

Putting it all together, here's the code:

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

If using Java 8, Stream API offers a concise alternative:

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());
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template