首页 > Java > java教程 > Java 9中Stream API添加了哪些新功能?

Java 9中Stream API添加了哪些新功能?

WBOY
发布: 2023-08-30 19:49:03
转载
930 人浏览过

Java 9中Stream API添加了哪些新功能?

In Java 9, Oracle Corporation has added four useful new methods to Stream API. Those methods are iterate(), ofNullable(), takeWhile() and dropWhile().

iterate()

The iterate() can be used as stream version replacement of traditional for-loops. This method has improved by adding another parameter, the Predicate interface that allows us to stop these endless numbers based on conditions defined with the Predicate interface.

Example

import java.util.stream.Stream;
public class StreamIterateMethodTest {
   public static void main(String[] args) {
      Stream.<strong>iterate</strong>(1, i -> i < 5, i -> i + 1).<strong>forEach</strong>(System.out::println); <strong>// iterate()</strong>
   }
}
登录后复制

输出

<strong>1
2
3
4</strong>
登录后复制
登录后复制

ofNullable()

ofNullable()方法在元素不为null时返回一个stream对象。否则,返回一个空的stream

示例

import java.util.stream.Stream;
public class StreamOfNullableMethodTest {
   public static void main(String[] args) {
      String str = "TutorialsPoint";
      Stream.<strong>ofNullable</strong>(str).<strong>forEach</strong>(System.out::println);   <strong> // ofNullable() method</strong>
   }
}
登录后复制

输出

<strong>TutorialsPoint
</strong>
登录后复制

takeWhile()

The parameter passed to a takeWhile() method is a Predicate interface. This method takes an element of stream object from left to right until the condition of the Predicate object is no longer fulfilled.

Example

import java.util.stream.Stream;
public class StreamTakeWhileMethodTest {
   public static void main(String[] args) {
      Stream.of(1, 2, 3, 4, 5)
         .<strong>takeWhile</strong>(i -> i < 5)         <strong>// takeWhile() method</strong>
         .<strong>forEach</strong>(System.out::println);
   }
}
登录后复制

输出

<strong>1
2
3
4</strong>
登录后复制
登录后复制

dropWhile()

传递给 dropWhile() 方法的参数也是一个 Predicate 接口。它与 takeWhile() 方法相反。该方法从左到右依次传递流对象中的每个元素,并忽略满足条件的所有元素。一旦条件不再满足,它将返回所有剩余的元素。

示例

import java.util.stream.Stream;
public class StreamDropWhileMethodTest {
   public static void main(String[] args) {
      Stream.of(3, 2, 1, 4, 6, 7, 8, 9, 10)
            .<strong>dropWhile</strong>(i -> i < 5)     <strong>// dropWhile() method</strong>
            .<strong>forEach</strong>(System.out::println);
   }
}
登录后复制

输出

<strong>6
7
8
9
10</strong>
登录后复制

以上是Java 9中Stream API添加了哪些新功能?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板