Converting loop to Java 8 streams

两盒软妹~` 提交于 2019-12-08 14:06:28

问题


How can I convert the following looping code to simple Java 8 streams?

List<String> headers = new ArrayList<>(); 
...   
int column = 0;

for(String text:headers){
    Cell cell = header.createCell(column++);
    cell.setCellValue(text);
}

回答1:


Streams won't be needed. Use an AtomicInteger and Iterable#forEach:

AtomicInteger column = new AtomicInteger(0);
headers.forEach(text -> header.createCell(column.getAndIncrement()).setCellValue(text));

Whether that's more readable is up to you.



来源:https://stackoverflow.com/questions/41604649/converting-loop-to-java-8-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!