Posts

Showing posts with the label hyphen-separated String to a List

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

In this section, we will show you h ow to c onvert hyphen-separated String to a List and  vice versa . 1. Hyphen-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 hyphen List < String > result = Arrays . asList ( str .split( " \\ s*- \\ s* " )); System . out .println( result ); } } Console Output: [India, USA, Japan, Russia] 2. List to Hyphen-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 ); } } Conso