EN
Java 8 - count unique objects eg Users and return Map<User, Integer> using Collectors.groupingBy
6 points
Quick solution:
xxxxxxxxxx
1
import java.util.ArrayList;
2
import java.util.List;
3
import java.util.Map;
4
import java.util.function.Function;
5
import java.util.stream.Collectors;
6
7
public class CountUsers {
8
9
public static void main(String[] args) {
10
11
List<User> users = new ArrayList<>();
12
users.add(new User("Kate", 24)); // Kate - 1st time
13
users.add(new User("John", 26));
14
users.add(new User("Ann", 25));
15
users.add(new User("Kate", 24)); // Kate - 2nd time
16
users.add(new User("Kate", 24)); // Kate - 3rd time
17
18
Map<User, Long> usersToCount = users.stream().collect(
19
Collectors.groupingBy(
20
Function.identity(), Collectors.counting()
21
)
22
);
23
24
usersToCount.forEach(
25
(user, count) -> System.out.println(user + ", " + count)
26
);
27
}
28
29
private static class User {
30
private final String name;
31
private final int age;
32
33
public User(String name, int age) {
34
this.name = name;
35
this.age = age;
36
}
37
38
public String getName() {
39
return name;
40
}
41
42
public int getAge() {
43
return age;
44
}
45
46
47
public boolean equals(Object o) {
48
if (this == o) return true;
49
if (o == null || getClass() != o.getClass()) return false;
50
51
User user = (User) o;
52
53
if (age != user.age) return false;
54
return name != null ? name.equals(user.name) : user.name == null;
55
}
56
57
58
public int hashCode() {
59
int result = name != null ? name.hashCode() : 0;
60
result = 31 * result + age;
61
return result;
62
}
63
64
65
public String toString() {
66
return "User{" +
67
"name='" + name + '\'' +
68
", age=" + age +
69
'}';
70
}
71
}
72
}
Output:
xxxxxxxxxx
1
User{name='Ann', age=25}, 1
2
User{name='John', age=26}, 1
3
User{name='Kate', age=24}, 3