streams - Removing Elements

case 1:

// streams/Randoms.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;

public class Randoms {
  public static void main(String[] args) {
    new Random(47).ints(5, 20).distinct().limit(7).sorted().forEach(System.out::println);
  }
}
/* Output:
6
10
13
16
17
18
19
*/

In Randoms.java, distinct() removed duplicates from the stream. Using distinct() is far less work than creating a Set to eliminate duplicates.

case 2:

// streams/Prime.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import static java.util.stream.LongStream.*;

import java.util.stream.*;

public class Prime {
  public static boolean isPrime(long n) {
    return rangeClosed(2, (long) Math.sqrt(n)).noneMatch(i -> n % i == 0);
// startInclusive - the (inclusive) initial value
// endInclusive - the inclusive upper bound
  }

  public LongStream numbers() {
    return iterate(2, i -> i + 1).filter(Prime::isPrime);
  }

  public static void main(String[] args) {
    // System.out.println(Math.sqrt(4)); // 2.0
    new Prime().numbers().limit(10).forEach(n -> System.out.format("%d ", n));
    System.out.println();
    new Prime().numbers().skip(90).limit(10).forEach(n -> System.out.format("%d ", n));
  }
}
/* Output:
2 3 5 7 11 13 17 19 23 29
467 479 487 491 499 503 509 521 523 541
*/

rangeClosed() includes the top boundary value. The noneMatch() operation returns true if no modulus produces zero, and false if any equal zero. noneMatch() quits after the first failure rather than trying them all.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Randoms.java

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Prime.java

4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html#noneMatch-java.util.function.LongPredicate-

5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html#rangeClosed-long-long-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值