Issue
I need to create a Map<String, Stream<String>> phoneNums(List<Stream<String>> numsList)
method to build a Map
of all phone numbers.
The key of Map
is code of network and value contains sorted list of phones.
Also need to remove all spaces, brackets and dashes from phone numbers.
For example for given:
["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"]
I should get:
{ "050"=["1234567", "2345678"],
"067"=["2143657"],
"093"=["1122334", "9182736", "9876543"],
"044"=["4356218"],
"loc"=["2241928", "7217345"],
"err"=["12345"] }
And I'm stuck right here. Please help.
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());
}
Solution
This is a good start:
return numsList.stream()
.flatMap(Function.identity())
.map(l ->l.replaceAll("[^0-9]",""))
But then you discard all the “error” numbers, and then you discard the local part of the number, so all that’s left is the area code:
.filter(n -> n.length()==10)
.map(n ->n.substring(0,3))
You need to keep all numbers, so you must not use filter
at all. Instead, you need to keep the entire number and make it available to the groupingBy
method, then choose a Map key based on the number’s length.
Joop is correct that Map values should not be Streams, since Streams can only be read once; Map<String, List<String>>
makes more sense:
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())));
}
The above logic uses the area code for a key if the length is 10; "loc" if the length is 7; "err" for any other length.
If you really need to return Streams as Map values, you can change the last line to:
Collectors.toList().stream())));
Answered By - VGR
Answer Checked By - Timothy Miller (JavaFixing Admin)