Search code examples
javaarraysspring-bootarraylistcasting

Reading 3 digits string numbers to an ArrayList?


I am reading values from a text files as shown below:

000,050,007
059,000,157
002,038,000

I get a line in the following block:

while ((line = reader.readLine()) != null) {
    System.out.println(line); // 000,050,007
    List<Integer> list = List.of(Integer.parseInt(line))
}

However, I cannot cast the 3 digit values (string) to Integer. So, how can I do this in an elegant way?

Update: I use the following approach, but I am not sure if there is a better way than using map() 2 times?

List<Integer> items= Stream.of(line.split(","))
                        .map(String::trim)
                        .map(Integer::parseInt)
                        .toList();

Solution

  • You need to split the line on comma before converting it to List of integers

    List<List<Integer>> list = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        System.out.println(line); // 000,050,007
        List<Integer> integers = Arrays.stream(line.split(","))
            .map(s -> Integer.parseInt(s.trim()))
            .toList();
        list.add(integers);
    }
    

    Note that having multiple map calls doesn't affect the performance, you just need to decide based on readability here.

    As you are using BufferedReader, you can replace while loop with stream

    List<List<Integer>> list = reader.lines().map(line ->
        Arrays.stream(line.split(","))
            .map(s -> Integer.parseInt(s.trim()))
            .toList()
    ).toList();