使用来自列表<流的流创建地图<String>>



我需要创建一个Map<String, Stream<String>> phoneNums(List<Stream<String>> numsList)方法来构建所有电话号码的Map

Map的密钥是网络代码,值包含电话的排序列表。

还需要删除电话号码中的所有空格、括号和破折号。

例如:

["093 987 65 43", "(050)1234567",   
"12-345"],    ["067-21-436-57", "050-2345678", "0939182736",   
"224-19-28"],    ["(093)-11-22-334", "044 435-62-18", "721-73-45"]

我应该得到:

{   "050"=["1234567", "2345678"],    
"067"=["2143657"],   
"093"=["1122334", "9182736", "9876543"],    
"044"=["4356218"],   
"loc"=["2241928", "7217345"],    
"err"=["12345"] }

我被困在这里了。请帮忙。

public Map<String, Stream<String>> phoneNums(List<Stream<String>> numsList) {
return numsList.stream()
.flatMap(Function.identity())
.map(l ->l.replaceAll("[^0-9]",""))
.filter(n -> n.length()==10)
.map(n ->n.substring(0,3))
.collect(Collectors.toMap());

}

这是一个良好的开端:

return numsList.stream()
.flatMap(Function.identity())
.map(l ->l.replaceAll("[^0-9]",""))

但是,你放弃了所有的"错误"号码,然后你放弃了号码的本地部分,所以剩下的就是区号:

.filter(n -> n.length()==10)
.map(n ->n.substring(0,3))

你需要保留所有的数字,所以你根本不能使用filter。相反,您需要保留整个数字,并使其可用于groupingBy方法,然后根据数字的长度选择Map键。

Joop认为Map值不应该是Streams是正确的,因为Streams只能读取一次;Map<String, List<String>>更有意义:

public Map<String, List<String>> phoneNums(List<Stream<String>> numsList) {
return numsList.stream()
.flatMap(Function.identity())
.map(l -> l.replaceAll("[^0-9]", ""))
.collect(Collectors.groupingBy(
n -> n.length() == 10 ? n.substring(0, 3)
: (n.length() == 7 ? "loc" : "err"),
Collectors.mapping(
n -> n.length() == 10 ? n.substring(3) : n,
Collectors.toList())));
}

如果长度为10,则上述逻辑将区号用于密钥"loc";如果长度是7"错误"对于任何其他长度。

如果您真的需要返回Streams as Map值,您可以将最后一行更改为:

Collectors.toList().stream())));

Stream是一个只有一次的迭代。因此,Map<String, List<String>>就是你将要得到的。有了List#stream(),你可以把每个列表都变成一个流,但除了操作上的损失,限制自己没有任何收获。

public Map<String, List<String>> phoneNums(List<Stream<String>> numsList) {
return numsList.stream()
.flatMap(Function.identity())
.map(l ->l.replaceAll("[^0-9]",""))
.filter(n -> n.length() == 10)
.groupingBy(n -> n.substring(0, 3), // Key.
n -> n.substring(3)); // Value.
}

groupingBy生成一个List,但添加第三个可选参数后,您可能会生成一个Stream。但未来的同事会发现阅读起来更加困难。

最新更新