繁体   English   中英

如何使用番石榴仿制药转换此地图?

[英]How can transform this map using guava generics?

说我有一个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);
        }

    }
}

如何using generic番石榴公用事业获得资源?

更一般地说,我希望能够从Map<U,V>一个Map<U,V'> ,其中类型V'的值将是V类对象的成员

你可以像这样简单地做到这一点。

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);

或者,没有可重用性:

Map<String,Integer> res = Maps.transformValues(map, new Function<A,Integer>() {
  @Override public Integer apply(A input) {
    return input.b;
  }
});

注意:结果是初始地图上的视图 您可能希望将其存储在新的HashMap (或ImmutableMap或任何其他Map )中。

请注意,使用Java 8,这变得更加嘈杂。 番石榴示例:

Map<String, Integer> res = Maps.transformValues(map, v -> v.b);

使用Java 8,您根本不需要Guava。 只需使用标准流方法:

Map<String, Integer> res = map.entrySet().stream()
    .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().b));

使用静态导入它甚至更短:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM