Java Stream How to - Filter elements in List and assign back








Question

We would like to know how to filter elements in List and assign back.

Answer

/*from   w w  w .j  av a2s.c o m*/
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] argv) throws Exception {
    List<String> argList = Arrays.asList("help", "v");

    Predicate<String> isHelp = (s) -> s.matches("(h|help)");

    argList = argList.stream().filter(isHelp.negate())
        .collect(Collectors.toList());

    System.out.println(argList);
  }

}

The code above generates the following result.