Currently I'm using something like :
String[]lines = textContent.split(System.getProperty("line.separator")); for(String tmpLine : lines){ //do something }
I'm not very glad of this method because it create an heavy array (let say textContent
can contain a book).
Is there any better solution to iterate over the lines of a String
?
forEach() Since Java 8, we can use the forEach() method to iterate over the elements of a list. This method is defined in the Iterable interface, and can accept Lambda expressions as a parameter.
Using the character iterator is probably the only correct way to iterate over characters, because Unicode requires more space than a Java char provides. A Java char contains 16 bit and can hold Unicode characters up U+FFFF but Unicode specifies characters up to U+10FFFF.
You could use :
BufferedReader bufReader = new BufferedReader(new StringReader(textContent));
And use the readLine()
method :
String line=null; while( (line=bufReader.readLine()) != null ) { }
To add the Java 8 way to this question:
Arrays.stream(content.split("\\r?\\n")).forEach(line -> /*do something */)
Of curse you can also use System.lineSeparator()
to split if you are sure that the file is comming from the same plattform as the vm runs on.
Or even better use the stream api even more agressiv with filter, map and collect:
String result = Arrays.stream(content.split(System.lineSeparator())) .filter(/* filter for lines you are interested in*/) .map(/*convert string*/) .collect(Collectors.joining(";"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With