Java 将条目写入数组速记
我是java新手,我有以下代码,是否有一种使用java8编写代码的有效方法: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
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();