Created
September 15, 2018 14:41
Star
You must be signed in to star a gist
Source code demonstration for article at https://kodemate.com/convert-array-to-list-and-vice-versa-in-java/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Assert; | |
import org.junit.Test; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import static org.hamcrest.core.Is.is; | |
/** | |
* KodeMate.com - Learn coding with crazy passion | |
* | |
* @author Pete Houston <contact@petehouston.com> | |
* @article Convert Array to List and vice versa | |
* @url https://kodemate.com/convert-array-to-list-and-vice-versa-in-java/ | |
*/ | |
public class ConversionTest { | |
private final Integer[] BASE_ARRAY = new Integer[] {1, 10, 99}; | |
private final List<Integer> RESULT_LIST = new ArrayList<Integer>() {{ | |
add(1); | |
add(10); | |
add(99); | |
}}; | |
private final List<Integer> BASE_LIST = new ArrayList<Integer>() {{ | |
add(14); | |
add(42); | |
add(2018); | |
}}; | |
private final Integer[] RESULT_ARRAY = new Integer[] {14, 42, 2018}; | |
@Test | |
public void Array2List_Using_Java_Core() { | |
// 1. loop / iteration | |
List<Integer> list1 = new ArrayList<>(); | |
for(Integer i: BASE_ARRAY) { | |
list1.add(i); | |
} | |
Assert.assertThat(list1, is(RESULT_LIST)); | |
// 2. Collection.addAll() method | |
List<Integer> list2 = new ArrayList<>(); | |
Collections.addAll(list2, BASE_ARRAY); | |
Assert.assertThat(list2, is(RESULT_LIST)); | |
// 3. Arrays.asList() method | |
List<Integer> list3 = Arrays.asList(BASE_ARRAY); | |
Assert.assertThat(list3, is(RESULT_LIST)); | |
// 4. Using Stream API in Java 8 | |
List<Integer> list4 = Arrays.stream(BASE_ARRAY).collect(Collectors.toList()); | |
Assert.assertThat(list4, is(RESULT_LIST)); | |
} | |
@Test | |
public void List2Array_Using_Java_Core() { | |
// 1. loop / iteration | |
Integer[] array1 = new Integer[BASE_LIST.size()]; | |
for(int i = 0; i < BASE_LIST.size(); i++) { | |
array1[i] = BASE_LIST.get(i); | |
} | |
Assert.assertArrayEquals(RESULT_ARRAY, array1); | |
// 2. List.toArray() method | |
Integer[] array2 = BASE_LIST.toArray(new Integer[BASE_LIST.size()]); | |
Assert.assertArrayEquals(RESULT_ARRAY, array2); | |
// 3. even better List.toArray() | |
Integer[] array3 = BASE_LIST.toArray(new Integer[0]); | |
Assert.assertArrayEquals(RESULT_ARRAY, array3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment