How to convert comma-separated String to List in Java

3 Answers

0 votes
import java.util.Arrays;
import java.util.List;
 
public class MyClass {
    public static void main(String args[]) {
        String str = "java, php, c, c++, python";
  
        List<String> list = Arrays.asList(str.split("\\s*,\\s*"));
   
        list.forEach(item->System.out.println(item));
    }
}
   
   
   
   
/*
run:
   
java
php
c
c++
python
   
*/

 



answered Dec 4, 2019 by avibootz
edited Nov 23, 2023 by avibootz
0 votes
import java.util.Arrays;
import java.util.List;
  
public class MyClass {
    public static void main(String args[]) {
        String str = "java, php, c, c++, python";
   
        List<String> list = Arrays.asList(str.split(" , "));
        
        // List<String> list = Arrays.asList(str.split(", ")); 
     
        list.forEach(item->System.out.println(item));
    }
}
    
    
    
    
/*
run:
    
java, php, c, c++, python
    
*/

 



answered Dec 4, 2019 by avibootz
edited Nov 23, 2023 by avibootz
0 votes
import java.util.Arrays;
import java.util.List;
 
public class MyClass {
    public static void main(String args[]) {
        String str = "java,c,c++,python";
         
        String[] array = str.split(",");
         
        List<String> list = Arrays.asList(array);
         
        System.out.println(list);
    }
}
 
 
 
 
/*
run:
 
[java, c, c++, python]
 
*/

 



answered Nov 23, 2023 by avibootz

Related questions

1 answer 165 views
1 answer 145 views
2 answers 210 views
1 answer 135 views
1 answer 145 views
1 answer 150 views
1 answer 158 views
...