Skip to content

Instantly share code, notes, and snippets.

@san81
Created April 11, 2017 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save san81/8ad56e4b9124f24260d1da0e8de18794 to your computer and use it in GitHub Desktop.
Save san81/8ad56e4b9124f24260d1da0e8de18794 to your computer and use it in GitHub Desktop.
When you are using Java 8 streams and trying to collect the results into a map, this example helps you explain how to resolve the key collisions
class StudentEntity {
String city;
String name;
public StudentEntity(String city, String name) {
this.city=city;
this.name=name;
}
public String getCity() { return city; }
public String getName() { return name; }
public String toString() { return "CITY:"+city+" NAME: "+name; }
}
public class TestMain {
public static void main(String ar[]){
List<StudentEntity> allStudents = new ArrayList<>();
allStudents.add(new StudentEntity("Sunnyvale","John"));
allStudents.add(new StudentEntity("Santa Clara","Jessi"));
allStudents.add(new StudentEntity("Sunnyvale","Kate"));
Map<String, StudentEntity> perCityStudents = allStudents.stream()
.collect(Collectors.toMap(StudentEntity::getCity, studentEntity -> studentEntity,
new BinaryOperator<StudentEntity>() {
@Override
public StudentEntity apply(StudentEntity studentEntity,
StudentEntity studentEntity2) {
return new StudentEntity(studentEntity.getCity(),studentEntity.getName() + " " + studentEntity2.getName());
}
}));
System.out.print(perCityStudents);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment