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

本小妞迷上赌 提交于 2020-08-17 06:21:34

问题


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.


回答1:


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());
}



回答2:


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.




回答3:


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());



回答4:


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);



回答5:


You can convert 2-d Integer array to List<List<Integer>> by using:

private static List<List<Integer>> arrayToList(Integer[][] array) {
    List<List<Integer>> lists = new ArrayList<>();
    for (Integer[] a : array) {
        List<Integer> list = new ArrayList<>();
        list.addAll(Arrays.asList(a));
        lists.add(list);
    }
    return lists;
}


来源:https://stackoverflow.com/questions/58337277/how-to-convert-int-string-to-listlistinteger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!