Java8 String To String List

Asked By 20 points N/A Posted on -
qa-featured

I have a list of channels like:

List <String> locations = Arrays.asList (“US: 5423”, “US: 6321”, “CA: 1326”, “AU: 5631”);

And I want to convert Map <String, List <String >> like this:

AU = [5631] CA = [1326] US = [5423, 6321]

How can I do that?

SHARE
Answered By 0 points N/A #318487

Java8 String To String List

qa-featured

You can do it like this:

Card <String, List <String >> locationMap = locations.stream ()

.map (s -> s.split (“:”))

.collect (Collectors.groupingBy (a -> a [0],

Collectors.mapping (a -> a [1], Collectors.toList ()));

A much better approach would be

private static final model DELIMITER = Pattern.compile (“:”);

Card <String, List <String >> locationMap = locations.stream ()

.map (s -> DELIMITER.splitAsStream (s) .toArray (String[] :: new))

.collect (Collectors.groupingBy (a -> a [0],

Collectors.mapping (a -> a [1], Collectors.toList ()));

Related Questions