写入数组速记的条目

时间:2017-10-25 13:45:22

标签: java java-8

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

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

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

return apps;

2 个答案:

答案 0 :(得分:2)

appSumList
  .stream()
  .map(ApplicationSummary::getName)
  .collect(Collectors.toList());

答案 1 :(得分:0)

是的,假设您要将name个对象的所有ApplicationSummary属性添加到apps List

类似的东西:

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()
    )
);`

修改

正如Juan Carlos指出的那样,如果想要包含{{}},则可能不需要在addAll apps上调用List {1}}每个name元素的属性:

appSumList