簡體   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