質問

Say I have a java class like

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 resusing genericguava` utilities ?

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

役に立ちましたか?

解決

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

他のヒント

Note that with Java 8 this becomes much less noisier. Guava example:

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

Also with Java 8 you don't need Guava at all. 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帰属
所属していません StackOverflow
scroll top