Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to iterate over the lines of a Java String?

Tags:

java

string

loops

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?

like image 449
alain.janinm Avatar asked Feb 13 '12 11:02

alain.janinm


People also ask

How do I efficiently iterate over each entry in a Java list?

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.

What type of a structure is the best way to iterate through the characters of a string?

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.


2 Answers

You could use :

BufferedReader bufReader = new BufferedReader(new StringReader(textContent)); 

And use the readLine() method :

String line=null; while( (line=bufReader.readLine()) != null ) {  } 
like image 131
Guillaume Polet Avatar answered Oct 13 '22 07:10

Guillaume Polet


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(";")); 
like image 41
leo Avatar answered Oct 13 '22 06:10

leo