Java Lambda 构造函数引用(二) ClassName::new

本文介绍了Java中的Lambda表达式,并通过一个实例展示了如何使用构造函数引用。示例中定义了一个TriFunction接口,然后创建了Color类,利用Color::new作为Lambda表达式,实现了通过TriFunction创建Color对象。在main方法中,分别使用直接的Lambda表达式和构造函数引用创建并打印了Color对象的属性值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java Lambda 构造函数引用(二) ClassName::new

@FunctionalInterface
public interface TriFunction<T, U, V, R> {
	R apply(T t, U u, V v);
}
public class Color {
	
	private Integer a;
	private Integer b;
	private Integer c;
	
	public Color() {
		
	}

	public Color(Integer a, Integer b, Integer c) {
		super();
		this.a = a;
		this.b = b;
		this.c = c;
	}


	public Integer getA() {
		return a;
	}


	public void setA(Integer a) {
		this.a = a;
	}


	public Integer getB() {
		return b;
	}


	public void setB(Integer b) {
		this.b = b;
	}


	public Integer getC() {
		return c;
	}


	public void setC(Integer c) {
		this.c = c;
	}
	
	public static Color getColor(Integer a, Integer b, Integer c, TriFunction<Integer, Integer, Integer, Color> f) {
		return f.apply(a, b, c);
	}


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TriFunction<Integer, Integer, Integer, Color> triFun = Color::new;
		Color color = triFun.apply(1, 2, 3);
		System.out.println(color.getA() + " " + color.getB() + " " + color.getC());
		
		Color cc = getColor(4, 5, 6, Color::new);
		System.out.println(cc.getA() + " " + cc.getB() + " " + cc.getC());
		
		TriFunction<Integer, Integer, Integer, Color> tf = (a, b, c) -> new Color(a, b, c);
		Color ccc = getColor(7, 8, 9, tf);
		System.out.println(ccc.getA() + " " + ccc.getB() + " " + ccc.getC());
		
	}

}
1 2 3
4 5 6
7 8 9

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值