-4

I am trying to get a String Collection in my Java code, so i'm trying something like this:

Collection c = new String[]{};

But i get this error: incompatible types: String[] cannot be converted to Collection.
Is there a way to convert String[] into Collection without doing something like this:

var array = new String[]{"Apple", "Banana"};
var arrayList = new ArrayList<String>();
for (String fruit : array) {
    arrayList.add(fruit);
}
Collection c = arrayList;

3 Answers3

2

Depends on the Collection. For example, if you want a List, use Arrays::asList

List<String> list = Arrays.asList(array);

or as a Collection:

Collection<String> list = Arrays.asList(array);

Be aware that this does not return a new List. It returns a fixed size view of the array you pass to the method, meaning that if the array changes, so does the list and vice versa. You cannot, however, change the length of the list.


There is no method for transforming an Array into a Set, but you can, for example, use a stream to achieve this:

Set<String> set = Arrays.stream(array).collect(Collectors.toSet());
Marv
  • 3,303
  • 2
  • 18
  • 42
1

Arrays are not Collections.

You will need to convert.

https://docs.oracle.com/javase/10/docs/api/java/util/Arrays.html

Arrays.asList(yourStringArray)
Wai Ha Lee
  • 7,664
  • 52
  • 54
  • 80
user1717259
  • 2,429
  • 5
  • 26
  • 38
0

Java 8+

String[] arr = { "A", "B", "C", "D" };
List<String> list = Arrays.stream(arr).collect(Collectors.toList());
fzen
  • 715
  • 3
  • 12