Stream a list of n-integers from a file to create an array of n objects

Suppose each object T can be created as

T tobj = new T(//int value);

So, to create an array of T [] from integers in a file, separated by a space, I do the following:

 BufferedReader br;
 FileReader fr;
 int[] arr;
 try{               
        fr = new FileReader(fo); // assume "fo" file name
        br = new BufferedReader(fr);
        arr = Arrays.stream(br.readLine().split("\\s")).mapToInt(Integer::parseInt).toArray();

 }catch(SomeException e){//something else}

T[] tobjarr = new T[arr.length];
    for(int i=0; i<arr.length; ++i)){
        tobjarr[i] = new T(arr[i]);
    }

1. Is this method effective in terms of time and space?

2. Is there any other way? if so, how does it compare with the above method?

+4
source share
2 answers

All in all, your approach is great. However, you can do this with a single-stream cascade . Compared to your original approach, this saves one iteration .

, , API - Javas, NIO. , Stream. , Files#lines, , .

, , :

String file = ...
Pattern separator = Pattern.compile("\\s");

try (Stream<String> lines = Files.lines(Paths.get(file))) {
    T[] values = lines                      // Stream<String> lines
        .flatMap(separator::splitAsStream)  // Stream<String> words
        .mapToInt(Integer::parseInt)        // IntStream values
        .mapToObj(T::new)                   // Stream<T> valuesAsT
        .toArray(T[]::new);
} catch (IOException e) {
    System.out.println("Something went wrong.");
}

, , . , :

List<T[]> valuesPerLine = Files.lines(Paths.get(file))  // Stream<String> lines
    .map(separator::splitAsStream)  // Stream<Stream<String>> wordsPerLine
    .map(lineStream -> {
        return lineStream                 // Stream<String> words
            .mapToInt(Integer::parseInt)  // IntStream values
            .mapToObj(T::new)             // Stream<T> valuesAsT
            .toArray(T[]::new);
    })                              // Stream<T[]> valuesPerLine
    .collect(Collectors.toList());

, IntStream Stream<T> mapToObj(T::new) ( map, , IntStream), . Stream<T> toArray(T[]::new).

+5
T[] array = Arrays.stream(br.readLine().split("\\s"))
    .map(s -> new T(Integer.parseInt(s)))
    .toArray(T[]::new)

EDIT: ,

+2

Source: https://habr.com/ru/post/1690729/


All Articles