EN
Java 8 - count unique objects eg Users and return Map<User, Integer> using Collectors.groupingBy
6
points
Quick solution:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CountUsers {
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User("Kate", 24)); // Kate - 1st time
users.add(new User("John", 26));
users.add(new User("Ann", 25));
users.add(new User("Kate", 24)); // Kate - 2nd time
users.add(new User("Kate", 24)); // Kate - 3rd time
Map<User, Long> usersToCount = users.stream().collect(
Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);
usersToCount.forEach(
(user, count) -> System.out.println(user + ", " + count)
);
}
private static class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (age != user.age) return false;
return name != null ? name.equals(user.name) : user.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
Output:
User{name='Ann', age=25}, 1
User{name='John', age=26}, 1
User{name='Kate', age=24}, 3