Created
April 11, 2017 23:46
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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