Java 8: Stream filter method

来源:互联网 发布:java long占几个字节 编辑:程序博客网 时间:2024/06/05 15:20

Sometimes, you might want to work with only a subset of the elements. To do so, you can use the filter method.

The filter method expects a lambda expression as its argument. However, the lambda expression passed to it must always return a boolean value, which determines whether or not the processed element should belong to the resulting Stream object.

For example, if you have an array of strings, and you want to create a subset of it which contains only those strings whose length is more than four characters, you would have to write the following code:

String[] myArray = new String[]{"bob", "alice", "paul", "ellie"};Arrays.stream(myArray)      .filter(s -> s.length() > 4)      .toArray(String[]::new);
0 0