Java - Convert colon-separated String to a List and List to a colon-separated String

In this section, we will show you how to convert colon-separated String to a List and vice versa.

1. Colon-separated String to List

Main.java

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {

String str = "India: USA: Japan: Russia";

//Remove whitespace and split by colon
List<String> result = Arrays.asList(str.split("\\s*:\\s*"));

System.out.println(result);
}
}


Console Output:
[India, USA, Japan, Russia]

2. List to Colon-separated String

Main.java

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {

List<String> list = Arrays.
asList("India", "USA", "Japan", "Russia");

String result = String.join(":", list);
System.out.println(result);
}
}


Console Output:
India:USA:Japan:Russia

Comments

Popular posts from this blog

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

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

Java - DES Encryption and Decryption example

Java - Blowfish Encryption and decryption Example

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

ReactJS - Bootstrap - Buttons

Top 5 Java ORM tools - 2024

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java - How to Count the Number of Occurrences of Substring in a String