How to apply some changes to each element in the list > structure using java 8 methods

I have some structures like list < < list < < double > > Listofdoubles I need to convert it to list < list < integer > > listofinteger I write code without using java 8 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 the second one with foreach, but not because I should be final How do I write this code using java 8 methods?

Solution

You can stream the "external" list to generate stream < list < double > Then, stream each "internal" list, convert each element to an integer, and collect the results Then only "external" streams are collected If you put them together, you'll get something like this:

List<List<Integer>> integerList = 
    doubleList.stream()
              .map(l -> l.stream()
                         .map(Double::intValue)
                         .collect(Collectors.toList()))
              .collect(Collectors.toList());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>