[java] Java: How to convert String[] to List or Set

How to convert String[] (Array) to Collection, like ArrayList or HashSet?

This question is related to java arrays collections converter

The answer is


java.util.Arrays.asList(new String[]{"a", "b"})

The easiest way is through

Arrays.asList(stringArray);

Whilst this isn't strictly an answer to this question I think it's useful.

Arrays and Collections can bother be converted to Iterable which can avoid the need for performing a hard conversion.

For instance I wrote this to join lists/arrays of stuff into a string with a seperator

public static <T> String join(Iterable<T> collection, String delimiter) {
    Iterator<T> iterator = collection.iterator();
    if (!iterator.hasNext())
        return "";

    StringBuilder builder = new StringBuilder();

    T thisVal = iterator.next();
    builder.append(thisVal == null? "": thisVal.toString());

    while (iterator.hasNext()) {
        thisVal = iterator.next();
        builder.append(delimiter);
        builder.append(thisVal == null? "": thisVal.toString());
    }

    return builder.toString();
}

Using iterable means you can either feed in an ArrayList or similar aswell as using it with a String... parameter without having to convert either.


It's a old code, anyway, try it:

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class StringArrayTest
{
   public static void main(String[] args)
   {
      String[] words = {"word1", "word2", "word3", "word4", "word5"};

      List<String> wordList = Arrays.asList(words);

      for (String e : wordList)
      {
         System.out.println(e);
      }
    }
}

Collections.addAll provides the shortest (one-line) receipt

Having

String[] array = {"foo", "bar", "baz"}; 
Set<String> set = new HashSet<>();

You can do as below

Collections.addAll(set, array); 

String[] w = {"a", "b", "c", "d", "e"};  

List<String> wL = Arrays.asList(w);  

If you really want to use a set:

String[] strArray = {"foo", "foo", "bar"};  
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);

output:

[foo, bar]

The easiest way would be:

String[] myArray = ...;
List<String> strs = Arrays.asList(myArray);

using the handy Arrays utility class. Note, that you can even do

List<String> strs = Arrays.asList("a", "b", "c");

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to converter

No converter found capable of converting from type to type How to convert datetime to integer in python Convert Int to String in Swift Concatenating elements in an array to a string Decimal to Hexadecimal Converter in Java Calendar date to yyyy-MM-dd format in java ffmpeg - Converting MOV files to MP4 Java: How to convert String[] to List or Set Convert xlsx to csv in Linux with command line How to convert string to long