如何使用 Java 流 API 从具有两个不同分隔符的字符串数组中解析和创建哈希图。
我有以下数组
String[] domaintCount = new String[]{ "900, google.com",
"400, mobile.yahoo.co.uk",
"100, mobile.amazon.com",
"100, samsung.com"
} ;
我想创建一个哈希图,其中每个单词作为键,数字作为值。 例如
google ,900,
com ,900,
mobile,400
等等..我想使用 Stream API 函数来做到这一点。
我做了这样的事情。基本思想是将字符串拆分为
<domain, number>
的映射,然后合并这些映射的值。
public static void main(String[] args) {
String[] domaintCount = new String[]
{
"900, google.com",
"400, mobile.yahoo.co.uk",
"100, mobile.amazon.com",
"100, samsung.com"
};
Function<String, Map<String, String>> stringParser = string -> {
String[] splitByComma = string.split(", ");
String num = splitByComma[0];
String[] domains = splitByComma[1].trim().split("\\.");
Map<String, String> stringStringHashMap = new HashMap<>();
for (String dom : domains) {
stringStringHashMap.put(dom, num);
}
return stringStringHashMap;
};
Map<String, String> collect = Stream.of(domaintCount)
.map(stringParser)
.map(Map::entrySet)
.flatMap(Set::stream)
.collect(groupingBy(Map.Entry::getValue))
.values().stream()
.flatMap(List::stream)
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1));
System.out.println(collect);
}
我会将其拆分然后收集到地图中。对于您的简单情况,我直接使用了 Java 中的 SimpleEntry。如果你的结果更复杂,我会创建一个 pojo:
Map<String, Double> yourMap = Arrays.stream(domaintCount)
.map(string -> {
String[] splitted = string.split(",");
return new AbstractMap.SimpleEntry<String, Double>(splitted[1].trim(), Double.valueOf(splitted[0].trim()));
})
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));
这样您也可以使用“,”和“,”。
Stream.of(domainCount)
.map(str->str.split(", "))
.collect(toMap(strArr->strArr[0].trim(), strArr->strArr[1].trim());
public static void main(String[] args) {
String[] domaintCount = new String[]{ "900, google.com",
"400, mobile.yahoo.co.uk",
"100, mobile.amazon.com",
"100, samsung.com"
};
Arrays.stream(domaintCount)
.map(s -> {
String[] strings = s.split(",");
return new Domain(Integer.valueOf(strings[0]), strings[1].trim());
})
.forEach(System.out::println);
}
static class Domain {
private Integer count;
private String dn;
public Domain(Integer count, String dn) {
this.count = count;
this.dn = dn;
}
@Override
public String toString() {
return String.format("[Domain, count: %d, dn: %s]", count, dn);
}
}