Explain Codes LogoExplain Codes Logo

Converting array to list in Java

java
array-conversion
stream-api
java-8
Nikita BarsukovbyNikita Barsukov·Sep 23, 2024
TLDR

To convert an array to a list in Java, use Arrays.asList for a fixed-size list or wrap it with a new ArrayList<>() for a modifiable list. Remember, when dealing with primitive arrays, additional steps are required because of autoboxing issues.

Example:

String[] array = {"apple", "banana", "cherry"}; List<String> list = new ArrayList<>(Arrays.asList(array)); // Java ensuring you get your daily fruits

Converting int[] to List<Integer>

Java 8's Stream API provides an elegant technique to convert int[] to List<Integer>.

int[] intArray = {1, 2, 3}; List<Integer> integerList = Arrays.stream(intArray) .boxed() // Integers need to wear boxing gloves to become List-compatible .collect(Collectors.toList());

Making List modifiable after conversion

Wrap the Arrays.asList() within a new ArrayList<>() to prevent potential UnsupportedOperationException when adding or removing elements.

List<String> modifiableList = new ArrayList<>(Arrays.asList(array)); // Ready for add/remove operations

Converting int[] to an immutable List<Integer>

For an immutable list, utilize Java 10's List.copyOf() or Java 8's Collectors.toUnmodifiableList().

List<Integer> unmodifiableList = List.copyOf(integerList); // This list is set in stone

Mind your type! (primitive vs wrapper class)

When using Arrays.asList(), always use the Integer wrapper class array with Arrays.asList() for smooth conversion. Primitive array types may require a manual conversion before use.

Integer[] numbers = {1, 2, 3}; List<Integer> numberList = Arrays.asList(numbers); // This is elementary, my dear Watson

Filling custom collections from arrays

With help from Java Streams, arrays can be collected into various collections like Set, Queue etc.

Set<Integer> set = Arrays.stream(intArray).boxed().collect(Collectors.toSet()); // Who needs duplicate numbers? Queue<Integer> queue = Arrays.stream(intArray).boxed().collect(Collectors.toCollection(LinkedList::new)); // Queue here for numbers

Key points to remember

Single-item beta testing: Arrays.asList(int[]) converts the whole array into a single list item.

Mutable or Immutable: Arrays.asList() returns a fixed-size list, i.e., no structural changes (add/remove). For a fully mutable list, resort to new ArrayList<>().

Array wrappers FTW: Arrays.asList(Integer[]) makes a List with each array element becoming a separate List element.

Primitives need a makeover: Avoid direct use of primitive arrays with Arrays.asList(). Instead, pre-convert these into their wrapper-class arrays or use Java 8 Stream operations.

Pro tips for level up

  • Leverage IDE features to offload mundane, procedural stuff.
  • Consult Effective Java book by Joshua Bloch to understand the nitty-gritty of Arrays.asList().
  • To quickly prototype and test : Use online Java environments like IdeOne.com.