List<String> get count of all elements ending with one of strings from another list

delica :

Let's say I have one list with elements like:

List<String> endings= Arrays.asList("AAA", "BBB", "CCC", "DDD");

And I have another large list of strings from which I would want to select all elements ending with any of the strings from the above list.

List<String> fullList= Arrays.asList("111.AAA", "222.AAA", "111.BBB", "222.BBB", "111.CCC", "222.CCC", "111.DDD", "222.DDD");

Ideally I would want a way to partition the second list so that it contains four groups, each group containing only those elements ending with one of the strings from first list. So in the above case the results would be 4 groups of 2 elements each.

I found this example but I am still missing the part where I can filter by all endings which are contained in a different list.

Map<Boolean, List<String>> grouped = fullList.stream().collect(Collectors.partitioningBy((String e) -> !e.endsWith("AAA")));

UPDATE: MC Emperor's Answer does work, but it crashes on lists containing millions of strings, so doesn't work that well in practice.

Eritrean :

If your fullList have some elements which have suffixes that are not present in your endings you could try something like:

    List<String> endings= Arrays.asList("AAA", "BBB", "CCC", "DDD");
    List<String> fullList= Arrays.asList("111.AAA", "222.AAA", "111.BBB", "222.BBB", "111.CCC", "222.CCC", "111.DDD", "222.DDD", "111.EEE");
    Function<String,String> suffix = s -> endings.stream()
                                                 .filter(e -> s.endsWith(e))
                                                 .findFirst().orElse("UnknownSuffix");
    Map<String,List<String>> grouped = fullList.stream()
                                               .collect(Collectors.groupingBy(suffix));
    System.out.println(grouped);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=304653&siteId=1