2012-08-16 14 views

Respuesta

81

Arrays.asList () haría el truco aquí.

String[] words = {"ace", "boom", "crew", "dog", "eon"}; 

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

Para convirtiendo al conjunto, se puede hacer como abajo

Set<T> mySet = new HashSet<T>(Arrays.asList(words)); 
7

La forma más sencilla sería:

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

utilizando la clase práctica Arrays utilidad. Tenga en cuenta, que incluso se puede hacer

List<String> strs = Arrays.asList("a", "b", "c"); 
2
java.util.Arrays.asList(new String[]{"a", "b"}) 
1

La forma más sencilla es a través de

Arrays.asList(stringArray); 
2

Es un código antiguo, de todos modos, probarlo:

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); 
     } 
    } 
} 
0
String[] w = {"a", "b", "c", "d", "e"}; 

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

Si realmente desea utilizar un conjunto:

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

de salida:

[foo, bar] 
7

Collections.addAll ofrece el más corto (una línea) recibo

Tener

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

Usted puede hacer como abajo

Collections.addAll(set, array); 
1

Si bien esto no es estrictamente una respuesta a esta pregunta creo Es útil.

Las matrices y colecciones pueden molestarse en convertirse a Iterable, lo que puede evitar la necesidad de realizar una conversión difícil.

Por ejemplo, escribí esto a unirse a las listas/matrices de cosas en una cadena con un separador

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(); 
} 

Usando iterables significa que puede ya sea de alimentación en un ArrayList o aswell similar a usarlo con un parámetro String... sin tener que convertir cualquiera.

Cuestiones relacionadas