[英]Stream and map a list to a map in java
I want to do something like the following with java 8 and lambda expression.我想用 java 8 和 lambda 表达式做类似下面的事情。
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.我想 stream 一个列表,取一个元素并为其获取另一个值。 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. (a,b)->b
是一个合并 function 以防重复。 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.警告:如果您有重复,则代码会引发预期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.