我从 Java 8 流集合和 lamba 表达式开始:
我想将一组条目转换为 map 。
在 java 7 中我会这样做:
JsonObject jsonObject=e.get(EQUATION_MAPPING_KEY).getAsJsonObject();
Set<Entry<String, JsonElement>> entries=jsonObject.entrySet();
ImmutableMap.Builder<Object, Object> builder=ImmutableMap.builder();
for(Entry<String, JsonElement> entry:entries){
builder.put(entry.getKey().toString(),entry.getValue().getAsBigDecimal());
}
put(EQUATION_MAPPING_KEY,builder.build());
到目前为止我已经试过了:
ImmutableMap<String,BigDecimal> map=entries.stream().collect(Collectors.toMap(Entry::getKey,Entry::getValue));
但是编译器会提示,因为我无法从非静态上下文中引用静态方法。
如何在 java 8 中实现相同的功能?
最佳答案
那是因为您将 Entry::getValue
设置为 Map 的
值,它是 JsonElement
而不是 BigDecimal
.需要在collect
中将其转化为BigDecimal
,例如:
Set<Entry<String, JsonElement>> entries = jsonObject.entrySet();
ImmutableMap<String, BigDecimal> map = entries.stream()
.collect(Collectors.collectingAndThen(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getAsBigDecimal()), ImmutableMap::copyOf));
关于java - 使用 Java 8 API 从 Set 到 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43746900/