Convert a list of strings of lists to a list of integers

Viewed 93

is there a smart way to convert a list of strings of list into a list of integer list?

I have this List:

["0,0,0,0", "1,1,1,1"]

and I would like to get:

 [[0,0,0,0],[1,1,1,1]]

I have tried this:

String comma = ",";
List<String> coords = Arrays.asList("0,0,0,0","1,1,1,1");
List<Integer> coordList =  Arrays.asList(coords.get(0).split(comma)).stream()
                                    .map(s -> Integer.parseInt(s))
                                    .collect(Collectors.toList());
1 Answers

I think you are looking to:

List<List<Integer>> coordList = coords.stream()
        .map(s -> Arrays.stream(s.split(comma))
                .map(Integer::valueOf)
                .collect(Collectors.toList()))
        .collect(Collectors.toList());

Or much better is to create a method and call it in map:

private List<Integer> convertStringToIntegers(String s) {
    String comma = ",";
    return Arrays.stream(s.split(comma))
            .map(Integer::valueOf)
            .collect(Collectors.toList());
}

then:

List<List<Integer>> coordList = coords.stream()
        .map(this::convertStringToIntegers)
        .collect(Collectors.toList());

Outputs

[[0, 0, 0, 0], [1, 1, 1, 1]]
Related