String operations - Learn Java 8 with examples
Split a String
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String str = "I love my country";
Arrays.stream(str.split(" "))
.collect(Collectors.toList())
.forEach(System.out::println);
}
}
Declare String which we are going to split.
The stream here is created from an existing array using the Arrays.stream() method . All array elements are converted to stream elements.
Here, split() method converts String based on whitespace and returns array of String.
You need to pass a special object to the method collect(). This object reads all the data from the stream, converts it to a specific collection, and returns it.
toList() method Returns a Collector that accumulates the input elements into a new List.
Finally, Iterate over List and print each elements to the console.
Console Output:
I
love
my
country
More examples,