如何通过Service调用Stream重构循环?

时间:2019-03-26 14:37:54

标签: java java-8 java-stream

您如何将这段代码重构为流?

for (ConditionEntity conditionEntity : dbData.getContent()) {
    AdminCondition adminCondition = 
            dataEntityMapper.conditionEntitytoModel(conditionEntity);

    this.myService.addBasicInterest(adminCondition); // <=== this is my Problem
    conditionList.add(adminCondition);
}

我到目前为止:

dbData.getContent().stream()
    .map(conditionEntity -> dataEntityMapper.conditionEntitytoModel(conditionEntity))
    .collect(conditionList);

寻求帮助!

4 个答案:

答案 0 :(得分:4)

我希望采用以下解决方案:

List<ConditionEntity> conditions = dbData.getContent().stream()
        .map(dataEntityMapper::conditionEntitytoModel)
        .collect(Collectors.toList());

conditions.forEach(this::addBasicInterest);

答案 1 :(得分:1)

List<AdminCondition > conditionList = new ArrayList<>();

dbData.getContent()
      .stream()
      .map(conditionEntity -> dataEntityMapper.conditionEntitytoModel(conditionEntity))
      .forEach(adminCondition  -> {
            this.myService.addBasicInterest(adminCondition);
            conditionList.add(adminCondition);
                   });

答案 2 :(得分:1)

只需执行以下操作即可。

dbData.getContent().stream()
  .map(conditionEntity -> {
      AdminCondition adminCondition = dataEntityMapper.conditionEntitytoModel(conditionEntity);
      this.myService.addBasicInterest(adminCondition);
  }) 
.collect(conditionList);

答案 3 :(得分:1)

我很可能会将其放入两个单独的语句中。

dbData.getContent().stream()
    .map(conditionEntity -> dataEntityMapper.conditionEntitytoModel(conditionEntity))
    .collect(conditionList);

conditionList.forEach(adminCondition -> this.myService.addBasicInterest(adminCondition))