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

后端 未结 4 702
暗喜
暗喜 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:01

    If you want to have 1 stream through a list, you need a way to manage 2 different states, you can do this by implementing Consumer to new class.

        class WordsInStr implements Consumer {
    
          ArrayList list = new ArrayList<>();
    
          @Override
          public void accept(String s) {
            Stream.of(s).filter(t -> t.contains("of")) //probably would be faster without stream here
                .map(t -> t.split(" ").length)
                .forEach(list::add);
          }
        }
    
        class LinePortionAfterFor implements Consumer {
    
          ArrayList list = new ArrayList<>();
    
          @Override
          public void accept(String s) {
            Stream.of(s) //probably would be faster without stream here
                .filter(t -> t.contains("for"))
                .map(t -> t.substring(t.indexOf("for")))
                .forEach(list::add);
          }
        }
    
        WordsInStr w = new WordsInStr();
        LinePortionAfterFor l = new LinePortionAfterFor();
    
        strs.stream()//stream not needed here
            .forEach(w.andThen(l));
        System.out.println(w.list);
        System.out.println(l.list);
    

提交回复
热议问题