streams - generate()

Another approach to creating a separate factory class:

// streams/Bubble.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.function.*;

public class Bubble {
  public final int i;

  public Bubble(int n) {
    i = n;
  }

  @Override
  public String toString() {
    return "Bubble(" + i + ")";
  }

  private static int count = 0;

  public static Bubble bubbler() {
    return new Bubble(count++);
  }
}
// streams/Bubbles.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.stream.*;

public class Bubbles {
  public static void main(String[] args) {
    Stream.generate(Bubble::bubbler).limit(6).forEach(System.out::println); // method reference.
  }
}
/* My Output:
Bubble(0)
Bubble(1)
Bubble(2)
Bubble(3)
Bubble(4)
Bubble(5)
*/
@FunctionalInterface
public interface Consumer<T>

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

This is a functional interface whose functional method is accept(Object).

references:

1. On Java 8 - Bruce Eckel

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

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

4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-

5. https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值