2011-11-07 19 views
9

¿Cómo puedo agregar elementos de dos conjuntos?Agregar elementos de dos conjuntos

If there's a set one (1, 3, 6, 8) 
And a set two (2, 4, 6, 8) 

¿Cómo consigo los elementos de esos dos juntos?

Output should be (1, 2, 3, 4, 6, 8) 

Esto es lo que he intentado:

Set<Integer> one = new HashSet(); 
one.add(1); 
one.add(3); 
// and so on 
Set<Integer> two = new HashSet(); 
two.add(2); 
two.add(4); 
// and so on 
Set<Integer> newSet = new HashSet(); 
newSet.add(one); 
newSet.add(two); 

return newSet; 

Y esto no funciona, ya que el método add sólo funciona para un solo número entero, no una colección de número entero. ¿Hay algún método donde pueda agregar dos juegos juntos?

También tengo que devolver el conjunto. ¿Cómo puedo hacer eso?

+2

intente utilizar addAll en lugar de agregar –

Respuesta

29

Uso Set.addAll()

Set<Integer> one = new HashSet<Integer>(); 
Set<Integer> two = new HashSet<Integer>(); 
Set<Integer> newSet = new HashSet<Integer>(one); 
newSet.addAll(two); 

También, usted debe escribir sus constructores (como el anterior).

convertir esto en un método, intente esto:

public static Set<Integer> addTwoSets(Set<Integer> one, Set<Integer> two) { 
    Set<Integer> newSet = new HashSet<Integer>(one); 
    newSet.addAll(two); 
    return newSet; 
} 

De hecho, vamos a ir completamente loco ... aquí es un método que va a tomar cualquier número de colecciones de cualquier tipo que se extiende el tipo deseado, y los combina en un conjunto:

public static <T> Set<T> merge(Collection<? extends T>... collections) { 
    Set<T> newSet = new HashSet<T>(); 
    for (Collection<? extends T> collection : collections) 
     newSet.addAll(collection); 
    return newSet; 
} 
2

Usted no quiere un conjunto. Como ha descubierto, no tienen elementos duplicados, por definición. Usted busca un Multiset (de hecho, un SortedMultiset por su apariencia), también conocido como Bag. Java no tiene una versión de fábrica, pero hay implementaciones de código abierto disponibles, por ejemplo, Google's.

EDITAR: También, desea hacer setOne.addAll(setTwo), no un elemento a la vez, como se comentó anteriormente, pero ese es el problema secundario.

+0

bien, en realidad quiero eliminar más adelante los duplicados. –

+0

Ummm, definitivamente NO es lo que preguntaste originalmente, ya que tu resultado de muestra tiene duplicados. –

+0

¿Cuál es la diferencia entre una * bolsa * y una * lista *? – Gabe

0

O alternativamente usar un ArrayList Ordenada:

ArrayList<Integer> list = new ArrayList<Integer>(one); 
list.addAll(two); 
Collections.sort(list); 
+0

Esto no eliminará los duplicados. – rakeeee

0

Como Bohemia mentioned, la mejor respuesta es usar Set.addAll(). Solo tenga en cuenta que, si no le importa sobrescribir uno de sus conjuntos, es más eficiente (al menos desde el punto de vista del tiempo del desarrollador: P) agregar un conjunto directamente a otro conjunto:

one.addAll(two); 
Cuestiones relacionadas