I have some structure like List<List<Double>> listOfDoubles I need to transform it to List<List<Integer>> listOfInteger. I wrote code without using Java 8. And it looks like:
List<List<Integer>> integerList = new ArrayList<>();
for (int i = 0; i < doubleList.size(); i++) {
for (Double doubleValue : doubleList.get(i)) {
integerList.get(i).add(doubleValue.intValue());
}
}
I tried to replace second for by foreach but can't because i should be final. How to write this code using Java 8 approach?
You could stream the "outer" list, generating a Stream<List<Double>. Then, stream each of the "inner" lists, convert each element to an Integer and collect the result. Then just collect the "outer" stream. If you bring it all together, you'd get something like this:
List<List<Integer>> integerList =
doubleList.stream()
.map(l -> l.stream()
.map(Double::intValue)
.collect(Collectors.toList()))
.collect(Collectors.toList());
In your code you lack the initialisation of the content. I would do it like this.
public List<List<Integer>> convert(List<List<Double>> doubles){
List<List<Integer>> toReturn = new ArrayList<>();
for(List<Double> ld: doubles){
List<Integer> temp = new ArrayList<>();
for(Double d: ld){
temp.add(d.intValue());
}
toReturn.add(temp)
}
return toReturn;
}
Basically, for each list in the double list of lists ( not really a matrix, but you could view it as one), you create a list in the integer list of lists and convert the single content.
P.S. this approach is more like Java 7 though, since a pure Java 8 would use streams as suggested in another answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With