Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

Java - create list from array

0 contributions
8 points

In java we have couple of ways to convert array to list.

1. Using Arrays.asList

String[] arr = {"Tim", "Jerry", "Ann"};
List<String> list = Arrays.asList(arr);

// [Tim, Jerry, Ann]
System.out.println(list.toString());

2. Using ArrayList constructor

String[] arr = {"Tim", "Jerry", "Ann"};
List<String> list = new ArrayList<>(Arrays.asList(arr));

// [Tim, Jerry, Ann]
System.out.println(list.toString());

3. Array with primitive type

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

// [1, 2, 3]
System.out.println(list.toString());

4. Using Guava

String[] arr = {"Tim", "Jerry", "Ann"};
List<String> list = Lists.newArrayList(arr);

// [Tim, Jerry, Ann]
System.out.println(list.toString());

5. Using Apache Commons Collections

String[] arr = {"Tim", "Jerry", "Ann"};
List<String> list = new ArrayList<>();
CollectionUtils.addAll(list, arr);

// [Tim, Jerry, Ann]
System.out.println(list.toString());

6. Write own converter with java generic

// generic method
public static <T> List<T> createListFromArray(T array[]) {
	List<T> list = new ArrayList<>();
	for (T t : array) {
		list.add(t);
	}
	return list;
}

String[] arr = {"Tim", "Jerry", "Ann"};
List<String> list = createListFromArray(arr);

// [Tim, Jerry, Ann]
System.out.println(list.toString());

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more