Tuesday, May 12, 2015

Array to Set & ViceVersa...


Convert Array to a Set

Using plain Java

Let’s first look at how to convert the array to a Set using plain Java:
?
1
2
3
4
5
@Test
public void givenUsingCoreJavaV1_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set<Integer> targetSet = new HashSet<Integer>(Arrays.asList(sourceArray));
}
Alternatively the Set can be created first and then filled with the array elements:
?
1
2
3
4
5
6
@Test
public void givenUsingCoreJavaV2_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set<Integer> targetSet = new HashSet<Integer>();
    Collections.addAll(targetSet, sourceArray);
}

Convert Set to Array

Using plain Java

Now let’s look at the reverse – converting an existing Set to an array:
?
1
2
3
4
5
@Test
public void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {
    Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
}




Source: http://www.baeldung.com/convert-array-to-set-and-set-to-array


No comments :

Post a Comment