Tuesday, January 21, 2025
HomeProgrammingConverting Array to List in Java

Converting Array to List in Java

To convert an array to a list in Java, you can use the Arrays.asList() method:

java
String[] array = {"apple", "banana", "cherry"};
List<String> list = Arrays.asList(array);

However, the list returned by Arrays.asList() is fixed-size and doesn’t support modification operations like add() or remove().

To create a mutable list, you can pass the result to a new ArrayList:

java
List<String> mutableList = new ArrayList<>(Arrays.asList(array));

This approach allows you to modify the list as needed.

See also  How to Print a List Without Brackets in Python

Alternatively, for primitive arrays, you can use Java 8 Streams:

java
int[] intArray = {1, 2, 3};
List<Integer> intList = Arrays.stream(intArray)
.boxed()
.collect(Collectors.toList());

This method converts the primitive array to a list of wrapper objects.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x