我知道如何“转换”一个简单的Java列表从Y -> Z,即:
List<String> x;
List<Integer> y = x.stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.toList());
现在我想对Map做基本相同的事情,即:
INPUT:
{
"key1" -> "41", // "41" and "42"
"key2" -> "42" // are Strings
}
OUTPUT:
{
"key1" -> 41, // 41 and 42
"key2" -> 42 // are Integers
}
解决方案不应局限于String -> Integer。就像上面的List示例一样,我想调用任何方法(或构造函数)。
另一种学习方法是通过collector .of()构建自定义收集器,不过这里的toMap() JDK收集器比较简洁(这里是+1)。
Map<String,Integer> newMap = givenMap.
entrySet().
stream().collect(Collector.of
( ()-> new HashMap<String,Integer>(),
(mutableMap,entryItem)-> mutableMap.put(entryItem.getKey(),Integer.parseInt(entryItem.getValue())),
(map1,map2)->{ map1.putAll(map2); return map1;}
));
如果你不介意使用第三方库,我的cyclops-react库有所有JDK集合类型的扩展,包括Map。我们可以直接使用'map'操作符转换map(默认情况下map作用于map中的值)。
MapX<String,Integer> y = MapX.fromMap(HashMaps.of("hello","1"))
.map(Integer::parseInt);
Bimap可用于同时转换键和值
MapX<String,Integer> y = MapX.fromMap(HashMaps.of("hello","1"))
.bimap(this::newKey,Integer::parseInt);