Skip to content

Commit 4ee6459

Browse files
committed
simplify callback example
1 parent 192459c commit 4ee6459

File tree

1 file changed

+23
-27
lines changed

1 file changed

+23
-27
lines changed

articles/components/grid/data-binding.adoc

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -118,41 +118,37 @@ public class PersonService {
118118
public static Stream<Person> fetch(
119119
String searchTerm, String sortOrder, int offset, int limit) {
120120
return PEOPLE.stream()
121-
.filter(person -> {
122-
if (searchTerm == null || searchTerm.isEmpty()) {
123-
return true;
124-
}
125-
126-
return person.name().toLowerCase().contains(searchTerm.toLowerCase());
127-
})
128-
.sorted((person0, person1) -> {
129-
if (sortOrder == null) {
130-
return 0;
131-
}
132-
return switch (sortOrder) {
133-
case "Name (A-Z)" ->
134-
Comparator.comparing(Person::name).compare(person0, person1);
135-
case "Name (Z-A)" ->
136-
Comparator.comparing(Person::name).reversed().compare(person0, person1);
137-
default ->
138-
0;
139-
};
140-
})
121+
.filter(createPredicate(searchTerm))
122+
.sorted(createComparator(sortOrder))
141123
.skip(offset)
142124
.limit(limit);
143125
}
144126
145127
public static int count(String searchTerm) {
146128
return (int) PEOPLE.stream()
147-
.filter(person -> {
148-
if (searchTerm == null || searchTerm.isEmpty()) {
149-
return true;
150-
}
151-
152-
return person.name().toLowerCase().contains(searchTerm.toLowerCase());
153-
})
129+
.filter(createPredicate(searchTerm))
154130
.count();
155131
}
132+
133+
private static Predicate<Person> createPredicate(String searchTerm) {
134+
if (searchTerm == null || searchTerm.isEmpty()) {
135+
return (person) -> true;
136+
}
137+
138+
return person -> person.name().toLowerCase().contains(searchTerm.toLowerCase());
139+
}
140+
141+
private static Comparator<Person> createComparator(String sortOrder) {
142+
if (sortOrder == null) {
143+
return 0;
144+
}
145+
Comparator<Person> comparator = switch (sortOrder) {
146+
case "Name (A-Z)" -> Comparator.comparing(Person::name);
147+
case "Name (Z-A)" -> Comparator.comparing(Person::name).reversed();
148+
default -> 0;
149+
};
150+
return comparator::compare;
151+
}
156152
}
157153
----
158154

0 commit comments

Comments
 (0)