添加到列表时有没有办法避免循环? [英] Is there a way to avoid loops when adding to a list?

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

问题描述

我想知道这样的代码:

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天全站免登陆