[英]How can transform this map using guava generics?
Say I have a java class like 说我有一个java类
public static class A{
int a;
int b;
int c;
public A(int a, int b, int c){
this.a=a; this.b=b; this.c=c;
}
}
public static void main(String[] args) {
final Map<String, A> map =Maps.newHashMap();
map.put("obj1",new A(1,1,1));
map.put("obj2",new A(1,2,1));
map.put("obj3",new A(1,3,1));
Map<String,Integer> res = Maps.newHashMap();
for(final String s : map.keySet()){
res.put(s,map.get(s).b);
}
}
}
How can I obtain res using generic
guava` utilities ? 如何
using generic
番石榴公用事业获得资源?
More generally I would like to be able to get from a Map<U,V>
a Map<U,V'>
where the values of type V'
would be members of objects of class V
更一般地说,我希望能够从
Map<U,V>
一个Map<U,V'>
,其中类型V'
的值将是V
类对象的成员
You can do this fairly simply like this. 你可以像这样简单地做到这一点。
Function<A, Integer> extractBFromA = new Function<A, Integer>() {
@Override public Integer apply(A input) {
return input.b;
}
}
...
Map<String,Integer> res = Maps.transformValues(map, extractBFromA);
Or, without the reusability in mind: 或者,没有可重用性:
Map<String,Integer> res = Maps.transformValues(map, new Function<A,Integer>() {
@Override public Integer apply(A input) {
return input.b;
}
});
Note: the result is a view on the initial map. 注意:结果是初始地图上的视图 。 You might want to store it in a new
HashMap
(or ImmutableMap
or any other Map
). 您可能希望将其存储在新的
HashMap
(或ImmutableMap
或任何其他Map
)中。
Note that with Java 8 this becomes much less noisier. 请注意,使用Java 8,这变得更加嘈杂。 Guava example:
番石榴示例:
Map<String, Integer> res = Maps.transformValues(map, v -> v.b);
Also with Java 8 you don't need Guava at all. 使用Java 8,您根本不需要Guava。 Just use standard stream methods:
只需使用标准流方法:
Map<String, Integer> res = map.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().b));
With static imports it is even shorter: 使用静态导入它甚至更短:
import static java.util.stream.Collectors.toMap;
// ...
Map<String, Integer> res = map.entrySet().stream()
.collect(toMap(e -> e.getKey(), e -> e.getValue().b));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.