Java 8: Stream filter method

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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章