Conversion entre un tableau et un ensemble en Java
1. Vue d'ensemble
Dans ce court article, nous allons examinerconverting between an array and a Set - d'abord en utilisant java, puis Guava et la bibliothèque Commons Collections d'Apache.
Cet article fait partie dethe “Java – Back to Basic” series ici par exemple.
2. ConvertirArray enSet
2.1. Utilisation de Java brut
Voyons d'abord commentturn 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));
}
Alternativement, lesSet peuvent être créés en premier, puis remplis avec les éléments du tableau:
@Test
public void givenUsingCoreJavaV2_whenArrayConvertedToSet_thenCorrect() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
Set targetSet = new HashSet();
Collections.addAll(targetSet, sourceArray);
}
2.2. Utiliser Google Guava
Ensuite, regardonsthe 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. Utilisation des collections Apache Commons
Enfin, effectuons la conversion à l'aide de la bibliothèque Commons Collection d'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. Convertir l'ensemble en tableau
3.1. Utilisation de Java brut
Regardons maintenant l'inverse -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. Utilisation de goyave
Suivant - la solution de goyave:
@Test
public void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {
Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
int[] targetArray = Ints.toArray(sourceSet);
}
Notez que nous utilisons l'APIInts de Guava, donc cette solution est spécifique au type de données avec lequel nous travaillons.
3.3 Using Commons Collections
Et enfin - transformons lesSet en un tableau à l'aide de la bibliothèque 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. Conclusion
L'implémentation de tous ces exemples et extraits de codecan be found over on Github - il s'agit d'un projet basé sur Maven, il devrait donc être facile à importer et à exécuter tel quel.