首页 > 解决方案 > Functional programming for ForLoop

问题描述

I am new to functional programming and needs some sort of guidance of writing the below piece of code using java

    public List<sampleEntity> sampleLetter(List<String> sampleIds) {
    List<sampleEntity> lstsampleEntity = new ArrayList<>();

    //Wanted to have the below for loop written using functional programming
            for (String sampleId : sampleIds) {
                lstsampleEntity.add(sampleLetter(sampleId));
            }

        return lstsampleEntity;
   }

标签: javalambda

解决方案


return sampleIds.stream()
    .map(s -> sampleLetter(s))
    .collect(Collectors.toList());

请注意,lambda 可以写为方法引用(this::sampleLetterTheClass::sampleLetter);你没有显示重载的方法声明,所以我只使用了在任何一种情况下都有效的 lambda。


推荐阅读