lines() method is a static method which returns out stream of lines extracted from a given multi-line string, separated by line terminators which are as follows:
Line terminators | Command |
---|
Line feed character | \n |
A carriage return character | \r |
A carriage return followed immediately by a line feed | \r\n |
Syntax:
public Stream<String> lines()
Return Type: Stream of string in order as present in multi-line
Illustration:
Input : "Geek \n For \n Geeks \n 2021"
Output :
Geek
For
Geeks
2021
Implementation:
Here we will be discussing out three examples to get better understanding of working of String class lines() method with data structures.
- forEach
- Converting stream of lines to ArrayList
- Converting stream of lines to array
Let’s discuss them one by one:
Example 1: forEach
Java
import java.util.stream.Stream;
public class GFG {
public static void main(String[] args)
{
String str
= " Geeks \n For \n Geeks \r Technical \r\n content \r writer \n Internship" ;
Stream<String> lines = str.lines();
lines.forEach(System.out::println);
}
}
|
Output Geeks
For
Geeks
Technical
content
writer
Internship
Example 2: Stream of lines to ArrayList using forEach
Java
import java.util.ArrayList;
import java.util.stream.Stream;
public class GFG {
public static void main(String[] args)
{
String str
= " Geeks \n For \n Geeks \r Technical \r\n content \r writer \n Internship" ;
Stream<String> lines = str.lines();
ArrayList<String> arrayList = new ArrayList<>();
lines.forEach(arrayList::add);
System.out.println(arrayList);
}
}
|
Output[ Geeks , For , Geeks , Technical , content , writer , Internship]
Example 3: Stream of lines to array
Java
import java.util.Arrays;
import java.util.stream.Stream;
public class GFG {
public static void main(String[] args)
{
String str
= " Geeks \n For \n Geeks \r Technical \r\n content \r writer \n Internship" ;
Stream<String> lines = str.lines();
Object[] array = lines.toArray();
System.out.println(Arrays.toString(array));
}
}
|
Output[ Geeks , For , Geeks , Technical , content , writer , Internship]