有没有一种方法可以避免在添加到列表时出现循环? [英] Is there a way to avoid loops when adding to a list?

查看:69
本文介绍了有没有一种方法可以避免在添加到列表时出现循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这样的代码:

List<String> list = new ArrayList<String>();
for(CustomObject co : objects) {
    list.add(co.getActualText());
}

可以用不同的方式写吗?我的意思是,当然在某个时候会有一个循环,但我想知道是否有我忽略的API使用情况

Can it be written differently? I mean of course at some point there will be a loop but I am wondering if there is an API usage I am ignoring

推荐答案

如果您使用Java 8,则可以利用Stream API:

If you use Java 8, you can take advantage of the Stream API:

List<String> list = objects.stream()
                           .map(CustomObject::getActualText)
                           .collect(Collectors.toList());

这篇关于有没有一种方法可以避免在添加到列表时出现循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆