Skip to content

Commit 01d82fc

Browse files
authored
Update record.md
1 parent f51225a commit 01d82fc

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

types/record.md

+87
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,90 @@ void main() {
5959
record User(String name, String occupation) {
6060
}
6161
```
62+
63+
## Comparison
64+
65+
```java
66+
import java.util.Comparator;
67+
import java.util.List;
68+
69+
void main() {
70+
71+
var users = List.of(
72+
new User("John", "Doe", 1230),
73+
new User("Lucy", "Novak", 670),
74+
new User("Ben", "Walter", 2050),
75+
new User("Robin", "Brown", 2300),
76+
new User("Amy", "Doe", 1250),
77+
new User("Joe", "Draker", 1190),
78+
new User("Janet", "Doe", 980),
79+
new User("Albert", "Novak", 1930));
80+
81+
var sorted = users.stream().sorted(Comparator.comparingInt(User::salary)).toList();
82+
System.out.println(sorted);
83+
}
84+
85+
record User(String fname, String lname, int salary) {
86+
}
87+
```
88+
89+
## Comparable
90+
91+
```java
92+
import java.util.List;
93+
94+
void main() {
95+
96+
var users = List.of(
97+
new User("John", "Doe", 1230),
98+
new User("Lucy", "Novak", 670),
99+
new User("Ben", "Walter", 2050),
100+
new User("Robin", "Brown", 2300),
101+
new User("Amy", "Doe", 1250),
102+
new User("Joe", "Draker", 1190),
103+
new User("Janet", "Doe", 980),
104+
new User("Albert", "Novak", 1930));
105+
106+
var sorted = users.stream().sorted().toList();
107+
System.out.println(sorted);
108+
}
109+
110+
record User(String fname, String lname, int salary) implements Comparable<User> {
111+
@Override
112+
public int compareTo(User u) {
113+
return this.lname.compareTo(u.lname);
114+
}
115+
}
116+
```
117+
118+
## Filtering
119+
120+
```java
121+
import java.util.List;
122+
import java.util.stream.Collectors;
123+
124+
void main() {
125+
126+
var users = List.of(
127+
User.of("John", "Doe", 1230),
128+
User.of("Lucy", "Novak", 670),
129+
User.of("Ben", "Walter", 2050),
130+
User.of("Robin", "Brown", 2300),
131+
User.of("Amy", "Doe", 1250),
132+
User.of("Joe", "Draker", 1190),
133+
User.of("Janet", "Doe", 980),
134+
User.of("Albert", "Novak", 1930));
135+
136+
var filtered = users.stream().filter(e -> e.salary() > 2000)
137+
.collect(Collectors.toList());
138+
System.out.println(filtered);
139+
}
140+
141+
record User(String fname, String lname, int salary) {
142+
public static User of(String fname, String lname, int salary) {
143+
return new User(fname, lname, salary);
144+
}
145+
}
146+
```
147+
148+

0 commit comments

Comments
 (0)