How to convert Map to Map ? (option : using guava)

前端 未结 6 870
礼貌的吻别
礼貌的吻别 2020-12-10 01:16

I have a Map the String key is nothing but numeric value like \"123\" etc. I\'m getting numeric value because this values are

6条回答
  •  伪装坚强ぢ
    2020-12-10 01:53

    UPDATE for Java 8

    You can use streams to do this:

    Map newMap = oldMap.entrySet().stream()
      .collect(Collectors.toMap(e -> Long.parseLong(e.getKey()), Map.Entry::getValue));
    

    This assumes that all keys are valid string-representations of Longs. Also, you can have collisions when transforming; for example, "0" and "00" both map to 0L.


    I would think that you'd have to iterate over the map:

    Map newMap = new HashMap();
    for(Map.Entry entry : map.entrySet()) {
       newMap.put(Long.parseLong(entry.getKey()), entry.getValue());
    }
    

    This code assumes that you've sanitized all the values in map (so no invalid long values).

    I'm hoping there is a better solution.

    EDIT

    I came across the CollectionUtils#transformedCollection(Collection, Transformer) method in Commons Collection-Utils that looks like it might do what you want. Scratch that, it only works for classes that implement Collection.

提交回复
热议问题