Cómo convertir una matriz a un Conjunto en Java


Me gustaría convertir una matriz a un Conjunto en Java. Hay algunas maneras obvias de hacer esto (es decir, con un bucle), pero me gustaría algo un poco más ordenado, algo como:

java.util.Arrays.asList(Object[] a);

¿Alguna idea?

Author: Bob Gilmore, 2010-06-17

16 answers

Así:

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

En Java 9+, si el conjunto no modificable está bien:

Set<T> mySet = Set.of(someArray);

En Java 10+, el parámetro generic type se puede inferir del tipo de componente arrays:

var mySet = Set.of(someArray);
 1012
Author: SLaks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-24 17:54:21
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

Eso es Colecciones.addAll (java.útil.Colección, T...) de JDK 6.

Además: ¿qué pasa si nuestra matriz está llena de primitivas?

Para JDK for para hacer el wrap y add-to-set en una pasada.

Para JDK > = 8, una opción atractiva es algo así como:

Arrays.stream(intArray).boxed().collect(Collectors.toSet());
 183
Author: JavadocMD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-13 23:39:53

Con Guayaba puedes hacer:

T[] array = ...
Set<T> set = Sets.newHashSet(array);
 112
Author: ColinD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-17 18:36:03

Java 8:

String[] strArray = {"eins", "zwei", "drei", "vier"};

Set<String> strSet = Arrays.stream(strArray).collect(Collectors.toSet());
System.out.println(strSet);
// [eins, vier, zwei, drei]
 57
Author: max,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-10 16:33:18

Varargs también funcionará!

Stream.of(T... values).collect(Collectors.toSet());
 34
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-05 20:48:34

{[6] {} En[7]}Java 8, tenemos la opción de usar Stream así. Podemos obtener stream de varias maneras:

Set<String> set = Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
System.out.println(set);

String[] stringArray = {"A", "B", "C", "D"};
Set<String> strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet());
System.out.println(strSet1);

Set<String> strSet2 = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet2);

El código fuente de Collectors.toSet() muestra que los elementos se agregan uno por uno a un HashSet pero la especificación no garantiza que será un HashSet.

" No hay garantías sobre el tipo, mutabilidad, serialización, o hilo-seguridad del conjunto devuelto."

Así que es mejor usar la opción posterior. La salida es: [A, B, C, D] [A, B, C, D] [A, B, C, D]

 19
Author: i_am_zero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-03 04:24:58

Después de hacer Arrays.asList(array) puedes ejecutar Set set = new HashSet(list);

Aquí hay un método de ejemplo, puede escribir:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}
 18
Author: Petar Minchev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-26 06:20:23

En Colecciones de Eclipse , lo siguiente funcionará:

Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);

Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();

Nota: Soy un committer para las Colecciones de Eclipse

 10
Author: Donald Raab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-21 03:32:30

Rápidamente: puedes hacer:

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

E invertir

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);
 6
Author: Pierre-Olivier Pignon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-04 09:30:37

He escrito lo siguiente del consejo anterior - robarlo... es agradable!

/**
 * Handy conversion to set
 */
public class SetUtil {
    /**
     * Convert some items to a set
     * @param items items
     * @param <T> works on any type
     * @return a hash set of the input items
     */
    public static <T> Set<T> asSet(T ... items) {
        return Stream.of(items).collect(Collectors.toSet());
    }
}
 5
Author: Ashley Frieze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-28 22:10:39

A veces usar algunas bibliotecas estándar ayuda mucho. Intente mirar las Colecciones de Apache Commons . En este caso, sus problemas simplemente se transforma en algo como esto

String[] keys = {"blah", "blahblah"}
Set<String> myEmptySet = new HashSet<String>();
CollectionUtils.addAll(pythonKeywordSet, keys);

Y aquí está la CollectionsUtils javadoc

 0
Author: mnagni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-04 17:13:21
    private Map<Integer, Set<Integer>> nobreaks = new HashMap();
    nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
    System.out.println("expected size is 3: " +nobreaks.get(1).size());

La salida es

    expected size is 3: 1

Cámbialo a

    nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));

La salida es

    expected size is 3: 3
 0
Author: Bruce Zu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-28 20:43:52

Use CollectionUtils o ArrayUtils de stanford-postagger-3.0.jar

import static edu.stanford.nlp.util.ArrayUtils.asSet;
or 
import static edu.stanford.nlp.util.CollectionUtils.asSet;

  ...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);
 0
Author: Olexandra Dmytrenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-21 21:26:45

{[7] {} En[8]}Java 10:

String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));

Set.copyOf devuelve un Set inmodificable que contiene los elementos del Collection dado.

El Collection dado no debe ser null, y no debe contener ningún elemento null.

 0
Author: Oleksandr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-22 10:11:53

new HashSet<Object>(Arrays.asList(Object[] a));

Pero creo que esto sería más eficiente:

final Set s = new HashSet<Object>();    
for (Object o : a) { s.add(o); }         
 -2
Author: Ben S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-14 23:09:24
Set<T> b = new HashSet<>(Arrays.asList(requiredArray));
 -3
Author: Satyendra Jaiswal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-12 12:38:33