Perform multiple unrelated operations on elements of a single stream in Java

后端 未结 4 699
暗喜
暗喜 2020-12-10 17:18

How can I perform multiple unrelated operations on elements of a single stream?

Say I have a List composed from a text. Each string in the

4条回答
  •  失恋的感觉
    2020-12-10 18:00

    You could use a custom collector for that and iterate only once:

     private static  Collector, List>> multiple() {
    
        class Acc {
    
            List strings = new ArrayList<>();
    
            List longs = new ArrayList<>();
    
            void add(String elem) {
                if (elem.contains("of")) {
                    long howMany = Arrays.stream(elem.split(" ")).count();
                    longs.add(howMany);
                }
                if (elem.contains("for")) {
                    String result = elem.substring(elem.indexOf("for"));
                    strings.add(result);
                }
    
            }
    
            Acc merge(Acc right) {
                longs.addAll(right.longs);
                strings.addAll(right.strings);
                return this;
            }
    
            public Pair, List> finisher() {
                return Pair.of(strings, longs);
            }
    
        }
        return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
    }
    

    Usage would be:

    Pair, List> pair = Stream.of("t of r m", "t of r m", "nice for nice nice again")
                .collect(multiple());
    

提交回复
热议问题