JDK8 lot of new features, such as lambda expression, function and use of stream programming flow, these new features, to put it down, after the use, such as the set list can be converted directly into the stream by the map object.
grammar:
Map map = list.stream.stream () collect (Collectors.toMap (list :: get object in the collection properties, list is an alias -> list is an alias));
Example:
Map<Integer , EmployeeTeacherCertificate> employeeTeacherCertificateMap =employeeTeacherCertificates.stream().collect(Collectors.toMap(EmployeeTeacherCertificate::getEmployeeId,cert->cert));
Description:
employeeTeacherCertificates List Collection Object
EmployeeTeacherCertificate: List is the collection of objects
Is not it simple.
However, if for example empId list in duplicate, it will error. as follows:
Error message saying, employeeId = value 4429 are repeated in the collection.
This time how to solve it?
We can use another method toMap of overloading. Method to weight with.
grammar:
Collectors.toMap(keyMapper, valueMapper, mergeFunction)
Source:
Parameter Description:
The first two parameters are the same as before the key and value attribute value obtained, when the third parameter is the processing method of key duplication, the following explanation Notes:
To put it simply:
For merging function, to resolve conflicts and provide the same key value associated therebetween to {@link Map # merge (Object, Object, BiFunction)}.
The combined function has two parameters, the first parameter value corresponding to the key before the current repeat, the second repeat key for the current value of the data current.
1, was repeated using the preceding value when the value back cover
Also it can be abbreviated like this:
Map<String, String> map = list.stream().collect(
Collectors.toMap(Student :: getClassName, Student :: getStudentName,
(key1 , key2)-> key2 ));
Also it can be abbreviated like this:
Map<String, String> map = list.stream().collect(
Collectors.toMap(Student :: getClassName, Student :: getStudentName,
(value1, value2 )->{
return value2;
}));
Kaige use the second option here:
The second simple and easy to understand.
Finally, to a summary of it.
to sum up:
These measures are implemented based on toMap overloads third argument! As to which method is best, I think we should depend on the specific business!
Welcome to learn together with the exchange. Kaige Java