Convertendo entre uma matriz e um conjunto em Java
1. Visão geral
Neste breve artigo, vamos dar uma olhada emconverting between an array and a Set - primeiro usando o java puro, depois Guava e a biblioteca Commons Collections do Apache.
Este artigo faz parte dethe “Java – Back to Basic” series aqui no exemplo.
2. ConvertaArray em aSet
2.1. Usando Plain Java
Vejamos primeiro comoturn the array to a Set using plain Java:
@Test
public void givenUsingCoreJavaV1_whenArrayConvertedToSet_thenCorrect() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
Set targetSet = new HashSet(Arrays.asList(sourceArray));
}
Como alternativa, oSet pode ser criado primeiro e, em seguida, preenchido com os elementos da matriz:
@Test
public void givenUsingCoreJavaV2_whenArrayConvertedToSet_thenCorrect() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
Set targetSet = new HashSet();
Collections.addAll(targetSet, sourceArray);
}
2.2. Usando o Google Guava
A seguir, vamos dar uma olhada emthe Guava conversion from array to Set:
@Test
public void givenUsingGuava_whenArrayConvertedToSet_thenCorrect() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
Set targetSet = Sets.newHashSet(sourceArray);
}
2.3. Usando coleções do Apache Commons
Finalmente, vamos fazer a conversão usando a biblioteca Commons Collection do Apache:
@Test
public void givenUsingCommonsCollections_whenArrayConvertedToSet_thenCorrect() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
Set targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceArray);
}
3. Converter conjunto em matriz
3.1. Usando Plain Java
Agora vamos olhar para o reverso -converting an existing Set to an array:
@Test
public void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {
Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
}
3.2. Usando goiaba
Em seguida - a solução Guava:
@Test
public void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {
Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
int[] targetArray = Ints.toArray(sourceSet);
}
Observe que estamos usando a APIInts do Guava, portanto, esta solução é específica para o tipo de dados com o qual estamos trabalhando.
3.3 Using Commons Collections
E finalmente - vamos transformar oSet em um array usando a biblioteca Apache Commons Collections:
@Test
public void givenUsingCommonsCollections_whenSetConvertedToArray_thenCorrect() {
Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
}
4. Conclusão
A implementação de todos esses exemplos e trechos de códigocan be found over on Github - este é um projeto baseado em Maven, portanto, deve ser fácil de importar e executar como está.