Java 将条目写入数组速记

Java 将条目写入数组速记,java,java-8,Java,Java 8,我是java新手,我有以下代码,是否有一种使用java8编写代码的有效方法: List<String> apps = new ArrayList<>(); for (ApplicationSummary applicationSummary : appSumList) { apps.add(appList.getName()); } return apps; List apps=new ArrayList(); for(应用程序摘要应用程序摘要:appSum

我是java新手,我有以下代码,是否有一种使用java8编写代码的有效方法:

List<String> apps = new ArrayList<>();

for (ApplicationSummary applicationSummary : appSumList) {
    apps.add(appList.getName());
}

return apps;
List apps=new ArrayList();
for(应用程序摘要应用程序摘要:appSumList){
apps.add(appList.getName());
}
返回应用程序;

是,假设要将
应用程序摘要
对象的所有
名称
属性添加到
应用程序
列表

比如:

apps
    // adding all to "apps"
    .addAll(
        // streaming list of "ApplicationSummary" items
        appSumList.stream()
        // mapping item to its name
        .map(ApplicationSummary::getName)
        // collecting as List (which is what will be passed to addAll)
        .collect(Collectors.toList()
    )
);`
编辑

如前所述,如果只想包含每个
appSumList
元素的
name
属性,则可能不需要在
应用程序上调用
addAll

// assigning value to "apps"
apps = 
    // streaming list of "ApplicationSummary" items
    appSumList.stream()
    // mapping item to its name
    .map(ApplicationSummary::getName)
    // collecting as List
    .collect(Collectors.toList();

apps.add(appList.getName())这不应该是
applicationSummary.add(appList.getName())什么是
appList
?您正在使用for each循环,但没有使用
applicationSummary
变量。为什么要使用
addAll
而不是直接向
apps
进行asign呢?@juancarlosmendoz是一个很好的观点。我只是“假设”应用程序
可能还包含其他内容。老实说,这里有很多假设……现在还不确定这是否正确。OP使用的是
appList.getName()
,所以我们不知道
ApplicationSummary
是否有
getName
,这是否是OP想要的。@JuanCarlosMendoza我想这是OP的一个输入错误
// assigning value to "apps"
apps = 
    // streaming list of "ApplicationSummary" items
    appSumList.stream()
    // mapping item to its name
    .map(ApplicationSummary::getName)
    // collecting as List
    .collect(Collectors.toList();