Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

12.2. IntSupplier / LongSupplier / DoubleSupplier / BooleanSupplier

IntSupplier - 有getAsInt()方法

LongSupplier - 有getAsLong()方法

DoubleSupplier - 有getAsDouble()方法

BooleanSupplier - 有getAsBoolean()方法。

		
package cn.netkiller.test;

import java.util.function.IntSupplier;
import java.util.stream.IntStream;

public class Test {
    public static void main(String[] args) {

        IntSupplier naturalGenerator = new IntSupplier() {
            int currentValue = 0;

            public int getAsInt() {
                return currentValue++;
            }
        };

        IntStream.range(0, 10).forEach((n) -> {
            System.out.println(naturalGenerator.getAsInt());
        });

    }
}
		
		

自定义 getAsInt 抽象方法,可以定制步进值

		
package cn.netkiller.test;

import java.util.function.IntSupplier;
import java.util.stream.IntStream;

public class Test {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread());

        IntSupplier naturalGenerator = new IntSupplier() {
            int currentValue = 1;

            public int getAsInt() {
                return currentValue *= 2;
            }
        };

        IntStream.range(0, 10).forEach((n) -> {
            System.out.println(naturalGenerator.getAsInt());
        });

    }

}