2

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.

apophis
  • 374
  • 3
  • 11
Peter Jacobsen
  • 618
  • 2
  • 6
  • 18
  • May be of use, but probably not: http://stackoverflow.com/questions/35131702/how-to-convert-java-list-of-objects-to-2d-array – Andrew Sep 09 '16 at 19:23
  • The `toArray` will create the second dimension of the array. Your missing statement needs to map a `String` to a `String[]`. You could use `String#split`. – 4castle Sep 09 '16 at 19:23
  • @4castle thx for your suggestion, it is simple as it is I was just over compicating it. – Peter Jacobsen Sep 09 '16 at 19:33

1 Answers1

3

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

EDIT:

List<String> lst = Arrays.asList(array);
String[][] arr2 = lst.stream().skip(5).limit(lst.size())
    .map(s -> s.split(":\\s")[1].split("\\s+")) // the mapper
    .toArray(String[][]::new);
David Pérez Cabrera
  • 4,960
  • 2
  • 23
  • 37