0

How do I restore List.toString back to List data type in Java

for eg:

List<String> abc = new ArrayList<String>(List.of("Why", "this", "Question")); 
        
String myStringValue = abc.toString();

System.out.println(myStringValue);

Output

[Why, this, Question]

What should be the best practice to restore the List from toString implementation?

List<String> restoredAbc = <??RestoreApi??> (myStringValue )

  • You can split the list to get a String Array and then convert it to List. – Sid Jul 15 '20 at 07:02
  • 1
    You can't reliably do that, because the `toString` output isn't designed to do that. For example `List.of("foo, bar")`and `List.of("foo", "bar")` are two different lists but produce the same `toString()` output. If none of the Strings contains a `,` you could use `substring()` and `split()` to get back to the list, though. – Joachim Sauer Jul 15 '20 at 07:03
  • 1
    Also, this *feels* like an [XY problem](http://xyproblem.info). Can you tell us what underlying problem you're trying to solve with this? – Joachim Sauer Jul 15 '20 at 07:03
  • @JoachimSauer the problem is need to persist the list String and restore it back. – Panther_Black Jul 15 '20 at 07:22
  • @Abhijeet: then `toString()` is not the correct tool for the job. Generally speaking `toString()` is useful for informational purposes (mostly for debugging). But it's **not** meant to losslessly store information. You need to use chose a data format, and I suggest an existing one like Java serialization, JSON or something like that. – Joachim Sauer Jul 15 '20 at 07:25

0 Answers0