Languages
[Edit]
EN

Java - create list from array

8 points
Created by:
Root-ssh
6322

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

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.