Languages
[Edit]
EN

Java - create list from array

8 points
Created by:
Root-ssh
68980

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());

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join