简体   繁体   English

将默认项添加到流集合

[英]Add a default item to a stream collection

I am performing some actions on a stream and returning an array list. 我正在流上执行一些操作并返回一个数组列表。 This is working without a problem but I need to do a final step to add an element if the array list is empty (nothing to do with options / nulls just part of the requirement) My way is a bit clunky and I wondered if it can be done in the stream operation instead? 这工作没有问题,但我需要做最后一步,如果数组列表为空,添加一个元素(与options / nulls无关只是要求的一部分)我的方式有点笨重,我想知道它是否可以而是在流操作中完成?

public ArrayList<String> getArrayList () {

        ArrayList<String> aL =  setOfStrings.stream()
            .filter(remove some)
            .filter(remove some more)
            .map(i -> createStringAbout(i))
            .collect(Collectors.toCollection(ArrayList::new));

        if (aL.size() < 1) {
            aL.add("No items passed the test");
        }

        return aL;
    }

So really I would like to do 所以我真的想做

return set.stream()...

is this possible ? 这可能吗 ?

Use collectingAndThen 使用collectingAndThen

.collect(Collectors.collectingAndThen(ArrayList::new, rs -> {
                    if(rs.size() < 1 ) {
                        rs.add("something");
                    }
                   return rs;
                })

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

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