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

第 12 章 函数式编程

目录

12.1. Supplier 供应型的接口
12.1.1. Supplier 作为方法参数使用
12.1.2. IntSupplier
12.1.3. LongSupplier
12.1.4. DoubleSupplier
12.1.5. BooleanSupplier
12.2. Consumer 消费型的接口
12.2.1. IntConsumer
12.2.2. 无返回值 Void
12.3. BiConsumer
12.4. BiFunction
12.5. Predicate 判断型的接口
12.6. Supplier / Consumer / Predicate 应用场景

12.1. Supplier 供应型的接口

		
Supplier<String> supplier = () -> "hello, world";
String result = supplier.get();
System.out.println(result);

Supplier stringSupplier = () -> new String("Hi Neo");
String string = stringSupplier.get();
System.out.println(string);

Supplier<LocalDateTime> currentTime = () -> LocalDateTime.now();  
LocalDateTime now = currentTime.get(); // 计算当前时间

Optional<String> optional = Optional.ofNullable("hello"); 
String orElseGet = optional.orElseGet(() -> "world");

Supplier userSupplier= () -> new User(1,"netkiller");  
User user=userSupplier.get();  
System.out.println(user.getName());  
		
		
		
package cn.netkiller.test;

import java.util.function.Supplier;

public class TestSupplier {
    private final int age = 24;

    TestSupplier() {
        System.out.println(age);
    }

    public static void main(String[] args) {
        Supplier<TestSupplier> supplier = TestSupplier::new;
        //调用get()方法,此时会调用对象的构造方法,即获得到真正对象
        supplier.get();
        System.out.println(supplier.get().test());

        TestSupplier test = supplier.get();
        System.out.println(test.test());
    }

    private String test() {
        return "Helloworld!!!";
    }
}		
		
		
			
package cn.netkiller.test;

import java.util.function.Supplier;

public class TestSupplier {
    private final int age = 24;
    private final String name;

    TestSupplier(String name) {
        this.name = name;
//        System.out.println(name);
    }

    public static void main(String[] args) {
        Supplier<String> stringSupplier = () -> {
            return "test1";
        };
        System.out.println(stringSupplier.get());

        Supplier<String> stringSupplier1 = () -> "test2";
        System.out.println(stringSupplier1.get());

        Supplier<TestSupplier> testSupplier = () -> new TestSupplier("Neo");
        System.out.println(testSupplier.get().name);

//        String name = "Netkiller";
//        Supplier<TestSupplier> testSupplier1 = (name) -> {new TestSupplier(name)};
//        System.out.println(testSupplier1.get().name);
//        System.out.println(test.test());
    }

    private String test() {
        return "Helloworld!!!";
    }
}
			
		

12.1.1. Supplier 作为方法参数使用

			
package cn.netkiller.test;

import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(Thread.currentThread());
        process(() -> {
            System.out.println(Thread.currentThread().getName() + " Process...");
            return "Test";
        });

        Supplier<String> stringSupplier1 = () -> "netkiller";
        process(stringSupplier1);

    }

    public static <T> void process(Supplier<T> supplier) {
//        System.out.println(Thread.currentThread().getName() + " Process...");

//        CompletableFuture<T> runAsync = CompletableFuture.supplyAsync(supplier);
//        runAsync.join();
//        System.out.println(variable.get());

        T value = supplier.get();
        System.out.println(value);
    }
}			
			
			

12.1.2. IntSupplier

IntSupplier - 有getAsInt()方法

		
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());
        });

    }

}		
		
			

12.1.3. LongSupplier

LongSupplier - 有getAsLong()方法

			
 	LongSupplier longSupplier1 = () -> LocalDate.now().toEpochDay();
    System.out.println(longSupplier1.getAsLong());

    LongSupplier longSupplier2 = () ->  Long.parseLong("1024");
    System.out.println(longSupplier2.getAsLong());      
      
	LongSupplier longSupplier3 = () -> {
		long num1 = 30L;
		long num2 = 50L;
		return num1 * num2;
	};
	System.out.println(longSupplier3.getAsLong());
	
	LongSupplier time = new Date()::getTime;
	System.out.println(time.getAsLong());		
			
			
			
	public static void main(String[] args) {
		String id = test(() -> new Random().nextLong());
		System.out.println(id);
	}

	public static String test(LongSupplier ls) {
		return "no. " + ls.getAsLong();
	}
			
			

12.1.4. DoubleSupplier

DoubleSupplier - 有getAsDouble()方法

			
	DoubleSupplier random = () -> new Random().nextDouble();
	System.out.println(random.getAsDouble());

	DoubleSupplier doubleSupplier = () ->  Double.parseDouble("123.0987");
      System.out.println(doubleSupplier.getAsDouble());      
      
      DoubleSupplier doubleSupplier1 = () -> {
    	double val1 = 35.30;
    	double val2 = 45.97;
    	return val1 * val2;
      };
      System.out.println(doubleSupplier1.getAsDouble());  

	DoubleSupplier random1 = new Random()::nextDouble;
	System.out.println(random1.getAsDouble());		
			
			

12.1.5. BooleanSupplier

BooleanSupplier - 有getAsBoolean()方法。

			
 	BooleanSupplier booleanSupplier1 = () -> LocalDate.now().isLeapYear();
      System.out.println(booleanSupplier1.getAsBoolean());

      BooleanSupplier booleanSupplier2 = () ->  "netkiller".length() > 5;
      System.out.println(booleanSupplier2.getAsBoolean());      
      
      BooleanSupplier booleanSupplier3 = () -> {
    	int num = 16;
    	if (num % 2 == 0) {
    	  return true;
    	}
    	return false;
      };
      System.out.println(booleanSupplier3.getAsBoolean());