-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathCollectorEx.java
More file actions
53 lines (38 loc) · 1.23 KB
/
CollectorEx.java
File metadata and controls
53 lines (38 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.zetcode;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collector;
public class CollectorEx {
public static void main(String[] args) {
List<User> persons = List.of(
new User("Robert", 28),
new User("Peter", 37),
new User("Lucy", 23),
new User("David", 28));
Collector<User, StringJoiner, String> personNameCollector =
Collector.of(
() -> new StringJoiner(" | "), // supplier
(j, p) -> j.add(p.getName()), // accumulator
(j1, j2) -> j1.merge(j2), // combiner
StringJoiner::toString); // finisher
String names = persons
.stream()
.collect(personNameCollector);
System.out.println(names);
}
}
class User {
private String name;
private int age;
User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return String.format("%s is %d years old", name, age);
}
}