Java 从字符串重构地图的函数解法
我一直在四处寻找,但没有找到使用Java8的优雅的功能解决方案。这就是我想解决的问题: 例如,我将映射“序列化”为单个字符串Java 从字符串重构地图的函数解法,java,lambda,functional-programming,java-8,Java,Lambda,Functional Programming,Java 8,我一直在四处寻找,但没有找到使用Java8的优雅的功能解决方案。这就是我想解决的问题: 例如,我将映射“序列化”为单个字符串 { type -> 'fruit', color -> 'yellow', age -> 5 } 将成为: type:fruit;color:yellow;age:5 现在,我想从字符串中重新创建原始贴图 Arrays.stream(input.split(";")) .map(v -> v.split(":"))
{ type -> 'fruit',
color -> 'yellow',
age -> 5 }
将成为:
type:fruit;color:yellow;age:5
现在,我想从字符串中重新创建原始贴图
Arrays.stream(input.split(";"))
.map(v -> v.split(":"))
.collect(Collectors.toMap(c -> c[0], c -> c.[1]);
请注意,上面的代码将导致NullPointerException
如果列表中没有“:”,可以通过以下方法解决此问题:
c.length > 1 ? c[1] : c[0]
但这感觉不对。使用Java8 API有什么建议或替代方案吗?这对我来说很有用:
class StreamToInflateStringToMap {
private static Function<String, String> keyMapper =
s -> s.substring(0, s.indexOf(":"));
private static Function<String, String> valueMapper =
s -> s.substring(s.indexOf(":") + 1);
public static Map<String, String> inflateStringToMap(String flatString) {
return Stream.of(flatString.split(";")).
collect(Collectors.toMap(keyMapper, valueMapper));
}
public static void main(String[] args) {
String flatString = "type:fruit;color:yellow;age:5";
System.out.println("Flat String:\n" + flatString);
Map<String, String> inflatedMap = inflateStringToMap(flatString);
System.out.println("Inflated Map:\n" + inflatedMap);
}
}
(请注意关于将可变
CharSequence
类型(如StringBuilder
)输入splitAsStream
方法的说明。)如果您有番石榴,可以使用
Splitter.on(';').withKeyValueSeparator(':').split(input)
如果你有
代码>或:
在值内?
Splitter.on(';').withKeyValueSeparator(':').split(input)