I have a list1 containing different strings which start with a string from another list (fooBarList).
List<String> list1 = Arrays.asList("FOO1234", "FOO1111", "BAR1", "BARRRRR");
List<String> fooBarList = Array.asList("FOO", "BAR");
I would like to create a Hashmap<String, List<String>> hm
which seperates the strings from the list1 depending on what they start with.
Result should look like this:
{FOO=["FOO1234",FOO1111"], BAR=["BAR1", "BARRRRR"]}
the fooBarList defines the different keys.
how do I achieve this with the help of streams? I just don't know how to do the step where I am basically saying: FOO1234 starts with FOO so check if key FOO exists and add it to the list else create a new list. ( I imagine I have to iterate over the fooBarList in the within the stream which just seems wrong to me )
/edit: sure with only 2 values in the fooBarList I could do simple checks if the string starts with "foo" then do this else do that. But what if my list contains 100s of strings.
A simple Collectors::groupingBy
should do the trick:
Map<String, List<String>> prefixGrouping = list1.stream()
.collect(
Collectors.groupingBy(
item -> fooBarList.stream().filter(item::startsWith).findFirst().orElse("")
)
);
Input:
list1=["FOO1234", "FOO1111", "BAR1", "BARRRRR", "LOL"], fooBarList=["FOO", "BAR"]
Output:
{""=["LOL"], "BAR"=["BAR1", "BARRRRR"], "FOO"=["FOO1234", "FOO1111"]}
You're looking for the prefix in the grouping function and if there is no prefix matching, then it will go into the emtpy String
bin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With