Java 8 applies a function to all Stream elements without breaking the sequence of streams

Is there a way in Java to apply a function to all elements Streamwithout breaking the chain Stream? I know I can call forEach, but this method returns void, not Stream.

+27
source share
6 answers

There are (at least) 3 ways. For the code example, I assumed that you want to call 2 user methods methodAand methodB:

a. Use peek():

list.stream().peek(x -> methodA(x)).forEach(x -> methodB(x));

Although the docs say they only use it for β€œdebugging,” it works (and it works now)

. map() A, :

list.stream().map(x -> {method1(x); return x;}).forEach(x -> methodB(x));

, , "" .

. forEach():

list.stream().forEach(x -> {method1(x); methodB(x);});

.

+28

Stream map().

:

List<String> strings = stream
.map(Object::toString)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
+4

, breaking the stream chain, Stream, Stream, . terminal operations, , , forEach Stream<T> , , , intermediate forEach forEach.

, :

 myStream.map(obj -> {obj.foo(); return obj;}

. , , Stream ( foo ):

  myStream.map(Obj::foo) // this will turn into Stream<T>, where T is 
           // the return type of foo, instead of Stream<Obj>

, map stateful, . , , . map stateless.

+1

, , - . , , :

IntStream.rangeClosed(40, 70).limit(20).mapToObj(i -> (Integer) i).map(item->item+3).map(item->item*2)... 

( StreamItemABC)

, - , :

private void applyMethod(ParameterX parX) {
 someStreamX().map(n -> methodX(n, parX))...
}

private StreamItemABC methodX (StreamItemABC item, ParameterX parX) {
  return notification;
}
+1

, Stream.peek. , . :

,

, peek, .

0

, - .

,

class Victim {
   private String tag;
   private Victim withTag(String t)
      this.tag = t;
      return this;
   }
}

List<Victim> base = List.of(new Victim());
Stream<Victim> transformed = base.stream().map(v -> v.withTag("myTag"));

( ), withTag ; .

0

Source: https://habr.com/ru/post/1017036/


All Articles