masterpeter2720 masterpeter2720 - 2 months ago 13
Java Question

Parsing data to 2D array in Java8

I have following data example

#data
1 name1
2 name2
3 name3
4 name4
1: 4 2
2: 3 1
3: 2 4
4: 1 3


The data has to part the first part is the 4 first lines should
String[]
array and the rest should be
String[][]
2d array.

Btw first line is escaped, for first part I need to parse the numbers of the names, I did following and it works fine:

String[] arr1 = lst.stream().skip(1).limit(4)
.map(elm -> elm.substring(0, elm.indexOf(" ")))
.toArray(String[]::new);


for second part, I want to find out how to parse the content to 2d array like following:

String[][] arr2 = {{"4", "2"},
{"3", "1"},
{"2", "4"},
{"1", "3"}};


Question: How to parse the last 4 lines to 2d array using Lambda expression?

String[][] arr2 = lst.stream().skip(5).limit(lst.size())
.// not sure how to parse data to 2d
.toArray(String[][]::new);


Note: I know how to do it the regular way, I want only to know how to do it in Lambda expression.

Answer

IMO a mapper String to String[] with a split by regex [:\s]+ must be enough

    String[] array = {"#data",
        "1 name1",
        "2 name2",
        "3 name3",
        "4 name4",
        "1: 4 2",
        "2: 3 1",
        "3: 2 4",
        "4: 1 3"};
    List<String> lst = Arrays.asList(array);
    String[][] arr2 = lst.stream().skip(5).limit(lst.size())
        .map(s -> s.split("[:\\s]+")) // the mapper
        .toArray(String[][]::new);