Java 8-流-收集时更新值

时间:2018-11-30 06:03:36

标签: java java-8 java-stream

在扩展上一个问题Java 8 - Calling a multi argument method from Collection.stream.map()的同时,如何在collect()处理之后收集stream().map()的同时更新值?

String designation = "Engineer";
String preFix = "PRE_FIX";
List<String> names = new ArrayList<>();
names.add("ABC");
names.add("DEF");
names.add("GHI");
System.out.println(
    names.stream()
         .map(name -> 
              MyClass.createReport(name, designation))
         .collect(ArrayList::new, ArrayList::add, ArrayList::addAll));

public static String createReport(String name, String designation) {
   return ("Name:" + name + " - Designation:" + designation);
}

输出:

[Name:ABC - Designation:Engineer, Name:DEF - Designation:Engineer, 
 Name:GHI - Designation:Engineer]

预期:

[PRE_FIX->Name:ABC - Designation:Engineer, PRE_FIX->Name:DEF - 
 Designation:Engineer, PRE_FIX->Name:GHI - Designation:Engineer]

2 个答案:

答案 0 :(得分:4)

使用另一个map()

System.out.println(
      names.stream()
           .map(name -> FolderDiffGenerator.createReport(name, 
                        designation))**
           .map(result -> preFix + "->" +result)**
           .collect(ArrayList::new, ArrayList::add, ArrayList::addAll));

答案 1 :(得分:1)

只需在调用之前将前缀添加到createReport

names.stream()
     .map(name -> preFix + "->" + MyClass.createReport(name, designation))
     .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

另一方面,.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);可以简化为.collect(toCollection(ArrayList::new));

names.stream()
     .map(name -> preFix + "->" + MyClass.createReport(name, designation))
     .collect(toCollection(ArrayList::new));