I want to do something like the following with java 8 and lambda expression.
Map<String, String> headers = service.getFieldNamesInOrder(eventType).stream()
.map(f -> serviceClassInfo.getNameforField(f).collect(Collectors.toMap(<streamed field>, <result of map>)));
Like this:
Map<String, String> headers = new HashMap<>();
for (String field : headerFieldNames) {
String name = service.getNameforField(field);
headers.put(field, name);
}
I want to stream a list, take one element and get another value for it. And afterwards I want to add the streamed element as key and the result from the method as value. Can anyone help?
Try this.
(a,b)->b
is a merge function in case of duplicates. It uses the most recent one.Map<String, String> headers = headerFieldNames.stream()
.collect(Collectors.toMap(field -> field,
field -> service.getNamefoField(field),
(a, b) -> b));
You should use something like
Map<String, String> headers = headerFieldNames.stream()
.collect(Collectors.toMap(f-> f, f -> service.getNameforField(f)));
Or
Map<String, String> headers = headerFieldNames.stream()
.collect(Collectors.toMap(Function.identity(), f-> service.getNameforField(f)));
Warning: It is code throws expection in case of you have duplicate.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.