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

前端 未结 10 982
醉酒成梦
醉酒成梦 2020-12-25 09:45

Currently I\'m using something like :

String[]lines = textContent.split(System.getProperty(\"line.separator\"));
for(String tmpLine : lines){
   //do somethi         


        
10条回答
  •  一生所求
    2020-12-25 10:21

    If you are using Java 1.8 (or Android) then try this:

    new BufferedReader(new StringReader(str)).lines().forEachOrdered((line) -> {
        // process each line as you like
    });
    

    Docs state

    The Stream is lazily populated, i.e., read only occurs during the terminal stream operation.

    Which means this runs quicker than other solutions that first generate a massive array of Strings before iteration can begin.

    If you are using Java 11 or later then the answer @Naman gave recommending String#lines() method is even cleaner and fast as well, see https://stackoverflow.com/a/50631579/215266

提交回复
热议问题