Skip to content

Commit e352870

Browse files
committed
feat(constructor-reference): demonstrate object creation using constructor references with streams
What - Added `MobilePhone` class with: - A single-argument constructor accepting `String name`. - Overridden `toString()` method for human-readable output. - Added `ConstructorReference` class to showcase: - Using `MobilePhone::new` as a constructor reference in a stream pipeline. - Mapping a list of `String` names into a list of `MobilePhone` objects. - Printing the resulting list with readable `toString()` output. Why - Constructor references (`ClassName::new`) provide a concise alternative to lambdas like `s -> new MobilePhone(s)`. - Improves code readability and avoids repetitive boilerplate when object construction aligns with functional interface signatures. - Demonstrates synergy between Java Streams and method references for elegant data transformations. Logic 1. Input Preparation: - Created `List<String> names = Arrays.asList("A", "B", "C")`. 2. Stream Transformation: - `names.stream()` → opens pipeline for processing. - `.map(MobilePhone::new)` → for each string, invokes `new MobilePhone(String)` using constructor reference. - `.collect(Collectors.toList())` → gathers all MobilePhone objects into a list. 3. Output: - `System.out.println(mobilePhoneList)` → prints list contents. - Because `toString()` was overridden, output is clear: `[MobilePhone{name='A'}, MobilePhone{name='B'}, MobilePhone{name='C'}]`. Real-life applications - Converting raw data (e.g., CSV strings, JSON fields) into domain objects via constructor references. - Creating DTOs or entity objects from IDs, names, or primitive values. - Useful in stream-heavy data pipelines for object instantiation without verbose lambdas. Notes - Equivalent lambda for `.map(MobilePhone::new)` is `.map(name -> new MobilePhone(name))`. - Overriding `toString()` is crucial for readable debugging and logging; otherwise, only memory references would appear. - Constructor references require the functional interface signature (here, `Function<String, MobilePhone>`) to match the constructor signature. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 0f8d6a2 commit e352870

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
Constructor Reference in Java
2+
3+
What is a Constructor Reference?
4+
- A constructor reference (ClassName::new) is shorthand to tell the compiler
5+
to use a specific constructor when creating objects.
6+
- Example: MobilePhone::new refers to the constructor of MobilePhone that takes a String parameter.
7+
- Equivalent to a lambda expression: name -> new MobilePhone(name).
8+
- More concise and expressive than writing the lambda manually.
9+
10+
Step-by-Step Explanation:
11+
12+
1. Creating a List of Names:
13+
List<String> names = Arrays.asList("A", "B", "C");
14+
→ Creates a list with values "A", "B", "C".
15+
16+
2. Mapping Each String to a MobilePhone:
17+
List<MobilePhone> mobilePhoneList = names.stream()
18+
.map(MobilePhone::new)
19+
.collect(Collectors.toList());
20+
- names.stream(): Converts list into a Stream.
21+
- map(MobilePhone::new): Creates a MobilePhone for each string using the constructor reference.
22+
- collect(Collectors.toList()): Collects MobilePhone objects into a List.
23+
24+
3. Printing the List:
25+
System.out.println(mobilePhoneList);
26+
- By default, prints object references (MobilePhone@hashcode).
27+
- To make output readable, override toString() in MobilePhone class.
28+
29+
Improving the Code:
30+
- Override toString() to display MobilePhone{name='A'} instead of default reference.
31+
*/
32+
33+
34+
import java.util.Arrays;
35+
import java.util.List;
36+
import java.util.stream.Collectors;
37+
38+
class MobilePhone {
39+
String name;
40+
41+
public MobilePhone(String name) {
42+
this.name = name;
43+
}
44+
45+
@Override
46+
public String toString() {
47+
return "MobilePhone{name='" + name + "'}";
48+
}
49+
}
50+
51+
public class ConstructorReference {
52+
public static void main(String[] args) {
53+
// List of names
54+
List<String> names = Arrays.asList("A", "B", "C");
55+
56+
// Constructor reference to create MobilePhone objects
57+
List<MobilePhone> mobilePhoneList = names.stream()
58+
.map(MobilePhone::new)
59+
.collect(Collectors.toList());
60+
61+
// Print the MobilePhone objects
62+
System.out.println(mobilePhoneList);
63+
}
64+
}
65+
66+
Expected Output:
67+
[MobilePhone{name='A'}, MobilePhone{name='B'}, MobilePhone{name='C'}]
68+
69+
Quick Recap:
70+
✔ Constructor reference simplifies object creation (MobilePhone::new).
71+
✔ Stream map() transforms Strings into MobilePhone objects.
72+
✔ Overriding toString() makes printed output readable.

0 commit comments

Comments
 (0)