6

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.

4
  • 1
    What if the second List contains both "FOO" and "FOO1". How do you decide which key to choose for "FOO1234"? Commented Feb 14, 2019 at 12:43
  • this can be ignored as it won't happen. I have several very unique keys. Commented Feb 14, 2019 at 12:45
  • Are these keys all having the same length (for example, 3 as in your example)? Commented Feb 14, 2019 at 12:46
  • no, the length can vary between the keys. Commented Feb 14, 2019 at 12:47

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.