Add code examples for "Convert Java Array to Iterable" (#14144)
* Add code examples for "Convert Java Array to Iterable" * fix formatting
This commit is contained in:
parent
c4334bf328
commit
6311a27f8c
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.array.conversions;
|
||||
|
||||
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class IntArrayToIterableConversionUtils {
|
||||
|
||||
public static Iterable<Integer> convertWithStreamToList(int[] array) {
|
||||
return Arrays.stream(array).boxed().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static Iterable<Integer> convertWithStreamIterator(int[] array) {
|
||||
return () -> Arrays.stream(array).iterator();
|
||||
}
|
||||
|
||||
public static Iterable<Integer> convertWithApacheCommonsAndJavaAsList(int[] array) {
|
||||
return Arrays.asList(ArrayUtils.toObject(array));
|
||||
}
|
||||
|
||||
public static Iterable<Integer> convertWithGuava(int[] array) {
|
||||
return Ints.asList(array);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.array.conversions;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.baeldung.array.conversions.IntArrayToIterableConversionUtils.*;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
|
||||
class IntArrayToIterableConversionUtilsUnitTest {
|
||||
|
||||
private int[] ints = new int[]{1, 2, 3, 4, 5};
|
||||
|
||||
@Test
|
||||
void whenConvertWithStreamToList_thenGetIterable() {
|
||||
Iterable<Integer> integers = convertWithStreamToList(ints);
|
||||
assertTrue("should be Iterable", integers instanceof Iterable);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenConvertWithStreamIterator_thenGetIterable() {
|
||||
Iterable<Integer> integers = convertWithStreamIterator(ints);
|
||||
assertTrue("should be Iterable", integers instanceof Iterable);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenConvertWithApacheCommonsAndJavaAsList_thenGetIterable() {
|
||||
Iterable<Integer> integers = convertWithApacheCommonsAndJavaAsList(ints);
|
||||
assertTrue("should be Iterable", integers instanceof Iterable);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenConvertWithGuava_thenGetIterable() {
|
||||
Iterable<Integer> integers = convertWithGuava(ints);
|
||||
assertTrue("should be Iterable", integers instanceof Iterable);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue