saidmohamed11
saidmohamed11

Reputation: 275

how to convert string of integers and Lists to arrayList

I have a situation where I want to convert a string into an ArrayList THAT CONTAINS INTEGERS AND OTHER ARRAYLISTS. In my string, I can have an arbitrary number of words which I want added into the ArrayList object:

String s = "[2,5,9,8,1,[5,7],9,8,[9,6,9,8],8,9]";

I did some work:

String testdata = "[25,645,[36,65],65]";
ArrayList<Integer> arrayInt = new ArrayList<>();
try (Scanner readFile = new Scanner(testdata)) {
    Pattern digitsPattern = Pattern.compile("(\\d+)");
    while (readFile.hasNextLine()) {
        Matcher m = digitsPattern.matcher(readFile.nextLine());
        while (m.find())
            arrayInt.add(Integer.valueOf(m.group(1)));
    }
}

The result is:

[25, 645, 36, 65, 65]

IWhat i want is this : [25,645,[36,65],65]

Upvotes: 1

Views: 64

Answers (2)

Pshemo
Pshemo

Reputation: 124275

Remove [ and ], then use Scanner with , delimiter (or use [, ] and , as Scanner's delimiters - this regex should do the trick [\\[\\],]+).

Also to avoid Integer.parseInt use Scanner#nextInt which returns int.

EDIT:

If you are willing to accept list which will contain numbers as floating point types like doubles you could try JSON serialization/deserialization tools like gson.

String testdata = "[25, 645, [36, 65], 65]";
List fromJson = new Gson().fromJson(testdata, List.class);
System.out.println(fromJson);

Output: [25.0, 645.0, [36.0, 65.0], 65.0].

Upvotes: 1

dave
dave

Reputation: 11985

An ArrayList<E> is typed, ie. you specify what single type <E> it can hold. For example, you have specified that arrayInt holds Integers, ie. E is Integer. This ArrayList cannot also then hold ArrayList<Integer>.

In order to meet your requirements you will need to define a type that can act as both a single Integer or a collection of Integers. This is usually implemented using the Composite Pattern.

Upvotes: 1

Related Questions