Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int[][] string to List<List<Integer>>

Tags:

java

junit5

There is a string like "[[7], [2,2,3]]".

How can I convert this string to a List<List<Integer>> Object?

This is to implement a parameter converter in JUnit5.

@CsvSource({
    "'[2,3,6,7]', 7, '[[7], [2, 2, 3]]'"
})

I want to convert the string "[[7], [2,2,3]]" to a List<List<Integer>> Object.

like image 467
Smoke Avatar asked Oct 11 '19 08:10

Smoke


People also ask

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .


4 Answers

Try this:

you split your input string at ], [ which gives you following rows:

row[0]: [[7
row[1]: 2,2,3]]

then you eliminate the '[[' ']]' strings

row[0]: 7
row[1]: 2,2,3

then you iterate over the elements of the rows by splitting them further at ',' and add each element to a list. When you are finished with one row you add it to the list of the listOfLists.

public List<List<Integer>> parseList(){
    String s  = "[[7], [2,2,3]]";

    return Arrays.stream(s.split("], \\["))
      .map(row -> row.replace("[[", "").replace("]]", ""))
      .map(row -> Arrays.stream(row.split(","))
        .map(Integer::parseInt).collect(Collectors.toList())
      ).collect(Collectors.toList());
}
like image 70
taygetos Avatar answered Oct 03 '22 13:10

taygetos


Disclaimer: I assume you meant to convert a given int[][] (or Integer[][]) and not parsing a String.

You can use a conventional for-loop or the stream API (since Java 8) for that.

There are actually a lot of variants to achieve this.


Stream

Assuming your source array is of type int[][]:

List<List<Integer>> result = Arrays.stream(source)     // Stream<int[]>
    .map(Arrays::stream)                               // Stream<IntStream>
    .map(IntStream::boxed)                             // Stream<Stream<Integer>>
    .map(values -> values.collect(Collectors.toList()) // Stream<List<Integer>>
    .collect(Collectors.toList())                      // List<List<Integer>>

Assuming it is of type Integer[][]:

List<List<Integer>> result = Arrays.stream(source)     // Stream<Integer[]>
    .map(Arrays::stream)                               // Stream<Stream<Integer>>
    .map(values -> values.collect(Collectors.toList()) // Stream<List<Integer>>
    .collect(Collectors.toList())                      // List<List<Integer>>

In case you are okay with the inner arrays being immutable (you can not add or remove items to them):

List<List<Integer>> result = Arrays.stream(source)     // Stream<Integer[]>
    .map(Arrays::asList)                               // Stream<List<Integer>>
    .collect(Collectors.toList())                      // List<List<Integer>>

Loop

Here is the variant for a conventional enhanced for loop:

List<List<Integer>> result = new ArrayList<>(source.length);
for (int[] innerValues : source) {
    List<Integer> values = new ArrayList<>(innerValues.length);
    for (int value : innerValues) {
        values.add(value);
    }
    result.add(values);
}

If source is Integer[][], just replace int with Integer in the above code.

You can also use forEach:

List<List<Integer>> result = new ArrayList<>(source.length);
for (int[] innerValues : source) {
    List<Integer> values = new ArrayList<>(innerValues.length);
    innerValues.forEach(values::add);
    result.add(values);
}

Or values = Arrays.asList(innerValues). But then they are immutable again.

like image 36
Zabuzard Avatar answered Oct 03 '22 14:10

Zabuzard


This can be done using Java 8 stream API this way:

Integer[][] dataSet = new Integer[][] {{...}, {...}, ...};
List<List<Integer> list = Arrays.stream(dataSet)
                               .map(Arrays::asList)
                               .collect(Collectors.toList());
like image 30
Dinesh K Avatar answered Oct 03 '22 13:10

Dinesh K


If input is string, then you can parse it using JSON Library.

Following code converts string to the output you are expecting.

JSONArray obj = (JSONArray) new JSONObject("{ \"array\" : [[7],[2,2,3]] }").get("array");

List<Object> list = obj.toList();
List<ArrayList<Integer>> newList = new ArrayList<ArrayList<Integer>>();

list.forEach(item -> {

    ArrayList<Integer> ar = (ArrayList<Integer>) item;

    newList.add(ar);
});

System.out.println(newList);
like image 29
Allabakash Avatar answered Oct 03 '22 13:10

Allabakash