How to convert comma-separated String to List?

前端 未结 24 1996
你的背包
你的背包 2020-11-22 16:58

Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for t

相关标签:
24条回答
  • 2020-11-22 17:29

    convert Collection into string as comma seperated in Java 8

    listOfString object contains ["A","B","C" ,"D"] elements-

    listOfString.stream().map(ele->"'"+ele+"'").collect(Collectors.joining(","))
    

    Output is :- 'A','B','C','D'

    And Convert Strings Array to List in Java 8

        String string[] ={"A","B","C","D"};
        List<String> listOfString = Stream.of(string).collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-22 17:31

    If a List is the end-goal as the OP stated, then already accepted answer is still the shortest and the best. However I want to provide alternatives using Java 8 Streams, that will give you more benefit if it is part of a pipeline for further processing.

    By wrapping the result of the .split function (a native array) into a stream and then converting to a list.

    List<String> list =
      Stream.of("a,b,c".split(","))
      .collect(Collectors.toList());
    

    If it is important that the result is stored as an ArrayList as per the title from the OP, you can use a different Collector method:

    ArrayList<String> list = 
      Stream.of("a,b,c".split(","))
      .collect(Collectors.toCollection(ArrayList<String>::new));
    

    Or by using the RegEx parsing api:

    ArrayList<String> list = 
      Pattern.compile(",")
      .splitAsStream("a,b,c")
      .collect(Collectors.toCollection(ArrayList<String>::new));
    

    Note that you could still consider to leave the list variable typed as List<String> instead of ArrayList<String>. The generic interface for List still looks plenty of similar enough to the ArrayList implementation.

    By themselves, these code examples do not seem to add a lot (except more typing), but if you are planning to do more, like this answer on converting a String to a List of Longs exemplifies, the streaming API is really powerful by allowing to pipeline your operations one after the other.

    For the sake of, you know, completeness.

    0 讨论(0)
  • 2020-11-22 17:31

    you can combine asList and split

    Arrays.asList(CommaSeparated.split("\\s*,\\s*"))
    
    0 讨论(0)
  • 2020-11-22 17:32

    In groovy, you can use tokenize(Character Token) method:

    list = str.tokenize(',')
    
    0 讨论(0)
  • 2020-11-22 17:34

    You can use Guava to split the string, and convert it into an ArrayList. This works with an empty string as well, and returns an empty list.

    import com.google.common.base.Splitter;
    import com.google.common.collect.Lists;
    
    String commaSeparated = "item1 , item2 , item3";
    
    // Split string into list, trimming each item and removing empty items
    ArrayList<String> list = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().splitToList(commaSeparated));
    System.out.println(list);
    
    list.add("another item");
    System.out.println(list);
    

    outputs the following:

    [item1, item2, item3]
    [item1, item2, item3, another item]
    
    0 讨论(0)
  • 2020-11-22 17:35

    Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:

    List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
    

    Or, using Guava:

    List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));
    

    Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).

    0 讨论(0)
提交回复
热议问题