Sunday 26 April 2020

Split comma separated string to list of strings

Approach 1: Split the string by comma and add each token to list.

private static List<String> getList_1(String str) {
         if (str == null || str.isEmpty()) {
                  return Collections.EMPTY_LIST;
         }

         List<String> list = new ArrayList<>();
         String[] tokens = str.split(",");

         for (String token : tokens) {
                  list.add(token);
         }

         return list;
}

Approach 2: Split the string by comma and use Arrays.asList to convert tokens array to list.
private static List<String> getList_2(String str) {
         if (str == null || str.isEmpty()) {
                  return Collections.EMPTY_LIST;
         }
         return Arrays.asList(str.split(","));
}

App.java
package com.sample.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class App {

 private static List<String> getList_1(String str) {
  if (str == null || str.isEmpty()) {
   return Collections.EMPTY_LIST;
  }

  List<String> list = new ArrayList<>();
  String[] tokens = str.split(",");

  for (String token : tokens) {
   list.add(token);
  }

  return list;
 }

 private static List<String> getList_2(String str) {
  if (str == null || str.isEmpty()) {
   return Collections.EMPTY_LIST;
  }
  return Arrays.asList(str.split(","));
 }

 public static void main(String args[]) {
  String str = "Hello,World,Java";

  List<String> result1 = getList_1(str);
  List<String> result2 = getList_2(str);

  System.out.println("result1 : " + result1);
  System.out.println("result2 : " + result2);
 }

}

Output
result1 : [Hello, World, Java]
result2 : [Hello, World, Java]



You may like

No comments:

Post a Comment