Skip to content

Commit 0366f87

Browse files
committed
[add] add example of ConstructorReference in module java 8
1 parent 3a582e2 commit 0366f87

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package com.brianway.learning.java8.lambda;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
import java.util.function.BiFunction;
7+
import java.util.function.Function;
8+
import java.util.function.Supplier;
9+
10+
/**
11+
* Created by brian on 17/2/28.
12+
* 构造函数引用
13+
*/
14+
public class ConstructorReference {
15+
16+
public static void main(String[] args) {
17+
//Apple()的构造函数
18+
Supplier<Apple> c1 = Apple::new;
19+
Apple a1 = c1.get();
20+
System.out.println(a1);
21+
22+
//Apple(int weight)的构造函数
23+
Function<Integer, Apple> c2 = Apple::new;
24+
Apple a2 = c2.apply(110);
25+
System.out.println(a2);
26+
27+
List<Integer> weights = Arrays.asList(7, 3, 4, 10);
28+
List<Apple> apples = map(weights, Apple::new);
29+
System.out.println("list of weights:");
30+
apples.stream().forEach(System.out::println);
31+
32+
//Apple(int weight, String color)的构造函数
33+
BiFunction<String, Integer, Apple> c3 = Apple::new;
34+
Apple a3 = c3.apply("green", 110);
35+
System.out.println(a3);
36+
}
37+
38+
public static List<Apple> map(List<Integer> list,
39+
Function<Integer, Apple> f) {
40+
List<Apple> result = new ArrayList<>();
41+
//TODO
42+
for (Integer e : list) {
43+
result.add(f.apply(e));
44+
}
45+
return result;
46+
}
47+
48+
public static class Apple {
49+
private int weight = 0;
50+
private String color = "";
51+
52+
public Apple() {
53+
}
54+
55+
public Apple(int weight) {
56+
this.weight = weight;
57+
}
58+
59+
public Apple(String color, int weight) {
60+
this.weight = weight;
61+
this.color = color;
62+
}
63+
64+
public Integer getWeight() {
65+
return weight;
66+
}
67+
68+
public void setWeight(Integer weight) {
69+
this.weight = weight;
70+
}
71+
72+
public String getColor() {
73+
return color;
74+
}
75+
76+
public void setColor(String color) {
77+
this.color = color;
78+
}
79+
80+
public String toString() {
81+
return "Apple{" +
82+
"color='" + color + '\'' +
83+
", weight=" + weight +
84+
'}';
85+
}
86+
}
87+
}

0 commit comments

Comments
 (0)