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:
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); } }
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());
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!