Can't make filter-> forEach-> compile in one thread?

I want to achieve something like this:

items.stream()
    .filter(s-> s.contains("B"))
    .forEach(s-> s.setState("ok"))
.collect(Collectors.toList());

then change the property from the filtered result, and then select the result in the list. However, the debugger says:

Cannot be called collect(Collectors.toList())for primitive type void.

Do I need 2 threads for this?

+6
source share
5 answers

forEachintended for terminal operation , and yes - you cannot do anything after calling it.

An idiomatic way would be to apply the transformation first, and then collect()everything to the desired data structure.

map, .

:

 items.stream()
   .filter(s -> s.contains("B"))
   .map(s -> s.withState("ok"))
   .collect(Collectors.toList());

withState - , , .


:

items.stream()
  .filter(s -> s.contains("B"))
  .collect(Collectors.toList());

items.forEach(s -> s.setState("ok"))
+5

forEach map.

 items.stream()
      .filter(s-> s.contains("B"))
      .map(s-> {s.setState("ok");return s;})
      .collect(Collectors.toList());

forEach collect - . , Stream<T>, - intermediate operation, - terminal operation.

+5

. , :

List<MyObj> toProcess = items.stream()
    .filter(s -> s.contains("B"))
    .collect(toList());

toProcess.forEach(s -> s.setState("ok"));
+4

forEach - , , . forEach , collect . , . map, , , . - :

items.stream()
     .filter (s -> s.contains("B"))
     .map    (s -> { s.setState("ok"); return s; }) // need to return a value here
     .collect(Collectors.toList());

peek, ( - ):

items.stream()
     .filter (s -> s.contains("B"))
     .peek   (s -> s.setState("ok")) // no need to return a value here
     .collect(Collectors.toList());
+3

.

, map:

List<YourClass> list = 
    items.stream()
         .filter(s-> s.contains("B"))
         .map(s-> {
                      s.setState("ok"); 
                      return s;
                  })
         .collect(Collectors.toList());
+2
source

All Articles