I'm having fun with Java's Stream library and lambdas.
The following code looks for persons within a list that have the same ID (which might indicate that something's wrong with the data) and prints out each group of people that share one ID.
I'm not sure if I'm doing this the most concise way, though.
This is the Person class:
public class Person {
private String name;
private String id;
public Person(String name, String id) {
this.name = name;
this.id = id;
}
public String getId() {
return id;
}
@Override
public String toString() {
return "Person [name=" + name + ", id=" + id + "]";
}
}
This is the code I'd love to get feedback on:
// Set up test data
List<Person> people = Arrays.asList(new Person("Michael", "1"),
new Person("Tobias", "2"), new Person("Nicole", "3"),
new Person("Sarah", "3"));
// Group persons by their ID
Map<String, List<Person>> peopleById = people.stream().collect(
Collectors.groupingBy(Person::getId));
// Print out groups of people that share one ID
peopleById
.values()
.stream()
.filter(peopleWithSameId -> peopleWithSameId.size() > 1)
.forEach(
peopleWithSameId -> System.out
.println("People with identical IDs: "
+ peopleWithSameId));
The code does what I want and I think it's readable but I doubt that this is the most I can get out of Java's functional features.
I wonder if you know a more elegant way to solve the problem.