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,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete