Supplier示例

Supplier示例Supplier 示例在 Java8 中 Supplier 是一个函数接口 不需要接收参数 返回一个结果 FunctionalIn T Tget Supplier 下面的示例用 Supplier 返回当前时间 importjava time LocalDateTim importjava time format DateTimeForm importjava util function T

Supplier示例

在Java 8中,Supplier是一个函数接口,不需要接收参数,返回一个结果

@FunctionalInterface public interface Supplier<T> { 
    T get(); } 

Supplier

下面的示例用Supplier,返回当前时间

import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.function.Supplier; public class Java8Supplier1 { 
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { 
    Supplier<LocalDateTime> s = () -> LocalDateTime.now(); LocalDateTime time = s.get(); System.out.println(time); Supplier<String> s1 = () -> dtf.format(LocalDateTime.now()); String time2 = s1.get(); System.out.println(time2); } } 

输出

2020-03-02T16:10:49. 2020-03-02 16:10:49 

返回Supplier

import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; public class Java8Supplier2<T> { 
    public static void main(String[] args) { 
    Java8Supplier2<String> obj = new Java8Supplier2(); List<String> list = obj.supplier().get(); } public Supplier<List<T>> supplier() { 
    // lambda // return () -> new ArrayList<>(); // constructor reference return ArrayList::new; } } 

工厂

返回Developer对象的简单工厂

import java.math.BigDecimal; import java.time.LocalDate; import java.util.function.Supplier; public class Java8Supplier3 { 
    public static void main(String[] args) { 
    Developer obj = factory(Developer::new); System.out.println(obj); Developer obj2 = factory(() -> new Developer("mkyong")); System.out.println(obj2); } public static Developer factory(Supplier<? extends Developer> s) { 
    Developer developer = s.get(); if (developer.getName() == null || "".equals(developer.getName())) { 
    developer.setName("default"); } developer.setSalary(BigDecimal.ONE); developer.setStart(LocalDate.of(2017, 8, 8)); return developer; } } 

Developer.java

import java.math.BigDecimal; import java.time.LocalDate; public class Developer { 
    String name; BigDecimal salary; LocalDate start; // for factory(Developer::new); public Developer() { 
    } // for factory(() -> new Developer("mkyong")); public Developer(String name) { 
    this.name = name; } // get, set, constructor, toString //... } 

输出

Developer{ 
   name='default', salary=1, start=2017-08-08} Developer{ 
   name='mkyong', salary=1, start=2017-08-08} 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224329.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午12:11
下一篇 2026年3月17日 下午12:11


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号