Converting array to list in Java
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:
Converting int[]
to List<Integer>
Java 8's Stream API provides an elegant technique to convert int[]
to List<Integer>
.
Making List
modifiable after conversion
Wrap the Arrays.asList()
within a new ArrayList<>()
to prevent potential UnsupportedOperationException
when adding or removing elements.
Converting int[]
to an immutable List<Integer>
For an immutable list, utilize Java 10's List.copyOf()
or Java 8's Collectors.toUnmodifiableList()
.
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.
Filling custom collections from arrays
With help from Java Streams, arrays can be collected into various collections like Set
, Queue
etc.
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.
Was this article helpful?