I have a toString()
representation of an ArrayList
.
Copying the toString()
value to clipboard, I want to copy it back into my IDE editor, and create the ArrayList
instance in one line. In fact, what I'm really doing is this:
My input looks like this:
[15.82, 15.870000000000001, 15.92, 16.32, 16.32, 16.32, 16.32, 17.05, 17.05, 17.05, 17.05, 18.29, 18.29, 19.16]
The following do not work:
Arrays.asList()
Lists.newArrayList()
Suggestions?
The toString() method returns a string representing the specified array and its elements.
You can override the toString method in a new created class but you should make sure the created class extends ArrayList. Then, you can override toString method.
Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.
Substring the braces away, split it on ,
(comma and space) and finally feed it to Arrays#asList()
.
String s = "[15.82, 15.870000000000001, 15.92, 16.32, 16.32, 16.32, 16.32, 17.05, 17.05, 17.05, 17.05, 18.29, 18.29, 19.16]";
List<String> list = Arrays.asList(s.substring(1, s.length() - 1).split(", "));
Note that this will work in your particular case, but not in all circumstances. You may for example have a list of strings of which at least one contains a subsequent comma and space. The split would then fail.
Generally speaking the toString()
of any objects does not contain information to reproduce the original object without any further information.
In your specific case the example could be produced by many different ArrayList
instances (as well as pretty much all other List
implementations which have identical toString()
) implementations.
As an extreme example, think of an ArrayList
that contains a single element which is the String
with the content 15.82, 15.870000000000001, 15.92, 16.32, 16.32, 16.32, 16.32, 17.05, 17.05, 17.05, 17.05, 18.29, 18.29, 19.16
. That ArrayList
would produce the exact same output as your original ArrayList
. And since two different inputs produce the same output, there's no way this function can be reversed without additional information.
If, however, we have additional information, such as the content type of the original ArrayList
, then it becomes possible in some cases. If we know that all elements of the List
were of type Double
, then it's actually pretty easy:
public static List<Double> stringToList(final String input) {
String[] elements = input.substring(1, input.length() - 1).split(", ");
List<Double> result = new ArrayList<Double>(elements.length);
for (String item : elements) {
result.add(Double.valueOf(item));
}
return result;
}
Granted, it's not a one-liner, but it's not too bad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With