Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using streams to read a text file and save to the BigInteger array

What would be the right way to read a text file, split numbers by , and save all of them to a BigInteger array?

BigInteger[] a = new BigInteger[1000];
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {

} catch (IOException e) {
    e.printStackTrace();
}

Can it be done directly or should you first save the whole file as a big String and then split it with streams?

String content = new String(Files.readAllBytes(Paths.get(filePath)));
like image 740
JohnC Avatar asked Dec 23 '22 20:12

JohnC


1 Answers

You can split the each string in stream by using , as delimiter, and then convert them into BigInteger array

BigInteger[] array = stream.map(str -> str.split(","))
                           .flatMap(Arrays::stream)
                           .map(BigInteger::new)
                           .toArray(BigInteger[]::new);

Or as approach suggested by @Lino says Reinstate Monica you can also use Pattern object to split the strings

Pattern pattern = Pattern.compile(",");

BigInteger[] array = stream.flatMap(pattern::splitAsStream)
                           .map(BigInteger::new)
                           .toArray(BigInteger[]::new);
like image 55
Deadpool Avatar answered Dec 29 '22 11:12

Deadpool