Enum array to string array [duplicate] - java

This question already has answers here:
Getting all names in an enum as a String[]
(26 answers)
Closed 3 years ago.
I'm having an Enum array. Now I want to convert it to a String array which contains the names of the enums returned by the method Enum#name(). Here's what I tried so far (The enum is called "Column".):
String[] stringArray = Arrays.asList(Column.values()).toArray(String[]::new);
I'm alway getting an ArrayStoreException. What can I do?

You need to stream the enum in order to first map the enum to String before creating the array:
String[] arrStr = Arrays.stream(FooEnum.values()) // create stream of enum values
.map(e -> e.toString()) // convert enum stream to String stream
.toArray(String[]::new); // convert stream to an array

Related

How do I convert List of String array to nested list of type String? [duplicate]

This question already has answers here:
Converting array to list in Java
(24 answers)
Java: is there a map function?
(6 answers)
Closed last month.
How do I convert List<String[]> to List<List<String>>?
List<String[]> allData = csv.readAll();
allData needs to be coverted in List<List<String>>.
You can use stream and Arrays::asList which will convert String[] to a List<String>, like this:
List<List<String>> response = allData.stream()
.map(Arrays::asList)
.collect(Collectors.toList()); // or just .toList();

How to transform String[] into collection? [duplicate]

This question already has answers here:
Converting array to list in Java
(24 answers)
How to convert an Array to a Set in Java
(19 answers)
Closed 3 years ago.
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;
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());
Arrays are not Collections.
You will need to convert.
https://docs.oracle.com/javase/10/docs/api/java/util/Arrays.html
Arrays.asList(yourStringArray)
Java 8+
String[] arr = { "A", "B", "C", "D" };
List<String> list = Arrays.stream(arr).collect(Collectors.toList());

How to create an immutable list from another list and separate items? [duplicate]

This question already has answers here:
What is an efficient and elegant way to add a single element to an immutable set?
(7 answers)
Returning a new ImmutableList that is an existing list plus an extra element
(2 answers)
Closed 4 years ago.
I am given a list and I want to add a single element of the same type that the list holds
List<String> list = List.of("a", "b", "c");
String item = "d";
I want to create an immutable list from both of them
List<String> combined = List.of(list.toArray(new String[0]), item);
The above of course does not compile because it's looking at the 2 argument overload where one argument is a String[] and the other is a String and want to create a List of size 2. What I want is to use the varargs signature of String, so to combine somehow the item into the array or "explode" the array and then the result will "merge" with the single argument.
What I tried?
List<String> arraylist = new ArrayList<>(list);
arraylist.add(item);
List<String> combined = List.copyOf(arraylist);
This is very inefficient. Can I do better?

How do i replace an array with an arraylist? [duplicate]

This question already has answers here:
Create ArrayList from array
(42 answers)
Closed 8 years ago.
How do I replace the following array with an ArrayList.
Employee[] companyTeam = {manager, engineer1, superviso1, accountant, intern };
You can do something like
List<Employee> companyTeam = Arrays.asList(manager, engineer1, superviso1, accountant, intern);
Employee[] companyTeam = {manager, engineer1, superviso1, accountant, intern };
List<Employee> list=Arrays.asList(companyTeam);// array to List
You already have an array, So you can use Arrays.asList(companyTeam) to convert array to List

How do I convert string array to ArrayList [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Assigning an array to an ArrayList in Java
java: how to convert this string to ArrayList?
How to convert a String into an ArrayList?
I have this String :
["word1","word2","word3","word4"]
The above text is not an array, but a string returned from server via GCM (Google Cloud Messaging) communication. More specific, inside a GCM class i have this:
protected void onMessage(Context context, Intent intent) {
String message = intent.getExtras().getString("cabmate");
}
The value of the String message is ["word1","word2","word3","word4"]
Is there a way to convert it in List or ArrayList in Java?
Arrays.asList(String[])
returns a List<String>.
Something like this:
/*
#invariant The "Word" fields cannot have commas in thier values or the conversion
to a list will cause bad field breaks. CSV data sucks...
*/
public List<String> stringFormatedToStringList(String s) {
// oneliner for the win:
return Arrays.asList(s.substring(1,s.length()-1).replaceAll("\"","").split(","));
// .substring removes the first an last characters from the string ('[' & ']')
// .replaceAll removes all quotation marks from the string (replaces with empty string)
// .split brakes the string into a string array on commas (omitting the commas)
// Arrays.asList converts the array to a List
}
String wordString = "[\"word1\", \"word2\", \"word3\", \"word4\"]";
String[] words = wordString.substring(1, wordString.length() - 2).replaceAll("\"", "").split(", ");
List<String> wordList = new ArrayList<>();
Collections.addAll(wordList, words);
This will do what you want. Do note that I purposely split on ", " to remove white space, it may be more prudent to call .trim() on each string in a for-each loop and then add to the List.

Categories