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

前端 未结 10 1050
醉酒成梦
醉酒成梦 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

    I believe you have a better API available starting with Java-11 where you can do the same using the String.lines() API which returns the stream of strings extracted from this string partitioned by line terminators.

    public Stream lines()
    

    Usage of the same could be:-

    Stream linesFromString = textContent.lines();
    linesFromString.forEach(l -> {  //do sth });
    

    Important API Note :-

    @implNote This method provides better performance than
              split("\R") by supplying elements lazily and
              by faster search of new line terminators.
    

提交回复
热议问题