简体   繁体   English

映射并在java流中应用

[英]map and apply in java stream

I currently have something like below 我目前有类似下面的内容

List<String> myNewList = myList
                           .stream()
                           .map(item->{
                             return mappedItem
                           })
                           .collect(Collectors.toList());
repository.save(myNewList);

In Optional, I can perform operations on the mapped item by using ifPresent method like below 在Optional中,我可以使用ifPresent方法对映射项执行操作,如下所示

myOptional
  .map(item -> {
    return mappedItem
  })
  .ifPresent(newItem -> {
    repository.save(newItem);
  });

I was wondering if I can do something like the above on stream. 我想知道我是否可以做上面这样的事情。 Rather than declaring myNewList , is there a way I can collect the new List and apply my function on the new list? 而不是声明myNewList ,有没有办法收集新的List并在新List应用我的函数?

Update: Based on the answer from @tagir-valeev, I modified my code as below 更新:根据@ tagir-valeev的回答,我修改了我的代码如下

myList
  .stream()
  .map(item->{
    return mappedItem
  })
  .collect(Collectors.collectingAndThen(Collectors.toList(),
    list -> {
      repository.save(list);
      return list;
    }
  ));

You can create your custom collector like this: 您可以像这样创建自定义收集器:

myList.stream().map(..)
      .collect(Collectors.collectingAndThen(Collectors.toList(), repository::save));

If save return type is void , it would be more ugly as you need to return something from collect : 如果save返回类型为void ,那么因为你需要从collect返回一些内容会更难看:

myList.stream().map(..)
      .collect(Collectors.collectingAndThen(Collectors.toList(), 
              list -> {repository.save(list);return list;}));

You may declare special method in your Repository class: 您可以在Repository类中声明特殊方法:

class Repository {
    Collector<MyItemType, ?, List<MyItemType>> saving() {
        return Collectors.collectingAndThen(Collectors.toList(), 
              list -> {this.save(list);return list;});
    }

    void save(List<MyItemType> list) { ... }
}

And use it: 并使用它:

myList.stream().map(..).collect(repository.saving());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM