Map String to list of string Input: String : Title; List Tags


Problem statement: 


  Need to map title to tags, e.g. title is "china man japan beijing bell" and tags are ["china man" "beijing bell"], output should be ["china man" "japan" "beijing bell"]


What I am doing:

List&lt;String&gt; getTitleSplits(String title, List&lt;String&gt; tags) {
        List&lt;String&gt; titleSplits = title.split(" "));
        List&lt;String&gt; ret = new ArrayList&lt;String&gt;();
        LinkedHashMap&lt;String, Boolean&gt; splitValueMap = new LinkedHashMap&lt;String, Boolean&gt;();
        for(String split : titleSplits) {
            splitValueMap.put(split, FALSE);
        }
        for(String titleSplit : titleSplits) {
                boolean flag = false;
                for(String tag : tags) {
                    if(tag.contains(titleSplit) || tag.contains(titleSplit.toLowerCase())) {
                        List&lt;String&gt; tagSplits = Arrays.asList(tag.split((" ")));
                        List&lt;String&gt; list = new ArrayList&lt;String&gt;();
                        for (String tagSplit : tagSplits) {
                            if (splitValueMap.get(tagSplit) == FALSE &amp;&amp;
                                    titleSplits.contains(tagSplit)) {
                                list.add(tagSplit);
                                splitValueMap.put(tagSplit, TRUE);
                                flag = true;
                            }
                        }
                        if(flag) {
                            ret.add(StringUtils.join(list, " ").trim());
                            splitValueMap.put(titleSplit, TRUE);
                            break;
                        }
                    }
                }
                if(!flag &amp;&amp; splitValueMap.get(titleSplit) == FALSE) {
                    ret.add(titleSplit);
                }
            }
        return ret;
}


Please review this.
This problem intrigued me, and it has aspects which relate to a real-world problem I am working on. Performance is a significant concern of mine, and reviewing your code, and the current answer by wassgren (+1), I suspect there's a better way to do it.

In both of your cases, you break the title down to words, and then build up the words in ways to see if they match tags. This creates a challenge which scales badly (I believe the solutions are about \$O(n t^2)\$ (n the size of the title, t the number of tags), and will have poor performance for reasonably sized titles, or tag sets.

A better way would be to only 'split' the title on the tag boundaries... locate each tag inside the title, and, if it is there, identify that location, then look in the next spots.

Still, this requires matching many tags, against many places in the title, which then becomes an order of \$O(nt)\$

Regular expressions, though, are able to significantly improve that by using Automata to match the text. A single regular expression on the title will approach \$O(n)\$ performance, and not significantly depend on the number of tags.

Thus, by building a complex regular expression, you can reduce the algorithmic complexity substantially. So, a regular expression like china man|beijing bell will match the first of those tags in the title.

Regular expressions can also work on word-boundaries, and be case insensitive. Thus, there is no need to do any splitting of the input, and conversion to lower-case....

Because regular expressions have structured orders of evaluation, we can build up a regex that encompasses all the required tags.

There are thus two parts... given a regular expression that matches all the tags, your code becomes simply:

    List&lt;String&gt; result = new ArrayList&lt;&gt;();
    Matcher mat = **SOME_PATTERN**.matcher(text);
    int lastPos = 0;
    while (mat.find()) {
        addNotEmpty(text, lastPos, mat.start(), result);
        result.add(mat.group());
        lastPos = mat.end();
    }
    addNotEmpty(text, lastPos, text.length(), result);

    return result.toArray(new String[result.size()]);


The code to build the regular expression is just a clever way of "orring" the tags:

    List&lt;String&gt; quoted = sources.stream().map(tag -&gt; "\\b" + Pattern.quote(tag) + "\\b")
            .collect(Collectors.toList());
    String pat = String.join("|", quoted);

    return new CompiledTagSet(Pattern.compile(pat, Pattern.CASE_INSENSITIVE), sources.toString());


Note, you look for word boundaries on the tag, and 'quote' it so that any tags containing special regex characters are not going to break things.... Then you concatenate them with the regex 'or' character |.

Finally, you compile it to be case-insensitive.

Putting this all together, you can have a system like:

package tagger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class TagSplitter {

    public static final class CompiledTagSet {
        private final Pattern pattern;
        private final String sources;


        private CompiledTagSet(Pattern pattern, String sources) {
            this.pattern = pattern;
            this.sources = sources;
        }

        private Pattern getPatterns() {
            return pattern;
        }

        @Override
        public String toString() {
            return sources;
        }

    }

    public static final CompiledTagSet compileTags(Collection&lt;String&gt; tags) {
        // strip out duplicate, empty, and null tags.
        List&lt;String&gt; sources = tags.stream()
                .filter(tag -&gt; tag != null)
                .map(tag -&gt; tag.trim())
                .filter(tag -&gt; !tag.isEmpty())
                .distinct()
                .collect(Collectors.toList());

        // THIS IS CRITICAL
        /*
         * Sort the 'tags' in reverse order alphabetically. The reason is as follows:
         * If one tag is a prefix of another, like "bobby" and "bobby tables", then we
         * want our regex to match "bobby tables" if it exists, and not just "bobby".
         * Add another tag "tables", and we have three: "bobby", "bobby tables" and
         * "tables". If we were to match the text:
         *     I am bobby tables
         * we want the match to be "bobby tables", and not "bobby" and "tables"
         * Java regular expressions are "alternate ordered" which means, if you have
         * OR conditions in the regex, the first one (left most) that matches, wins.
         * So, if we have the regular expression "bobby|bobby tables|tables" and match
         * that against "I am bobby tables", it will match "bobby" first.
         * 
         *  The regular expression "bobby tables|bobby|tables", on the other hand, will
         *  match "bobby tables" first.
         *  
         *  By sorting the tags in reverse order, longer tags will happen first.
         *  
         *  I believe this will also make track-back mechanisms faster in the automaton
         *  if closely related tags are closer together.
         */
        sources.sort(Comparator.reverseOrder());

        List&lt;String&gt; quoted = sources.stream().map(tag -&gt; "\\b" + Pattern.quote(tag) + "\\b").collect(Collectors.toList());
        String pat = String.join("|", quoted);

        return new CompiledTagSet(Pattern.compile(pat, Pattern.CASE_INSENSITIVE), sources.toString());
    }

    private static final void addNotEmpty(String text, int left, int right, List&lt;String&gt; target) {
        if (right &lt;= left) {
            return;
        }
        String candidate = text.substring(left, right).trim();
        if (candidate.isEmpty()) {
            return;
        }
        target.add(candidate);
    }

    public static String[] splitByTags(final String text, final CompiledTagSet tags) {

        List&lt;String&gt; result = new ArrayList&lt;&gt;();
        Matcher mat = tags.getPatterns().matcher(text);
        int lastPos = 0;
        while (mat.find()) {
            addNotEmpty(text, lastPos, mat.start(), result);
            result.add(mat.group());
            lastPos = mat.end();
        }
        addNotEmpty(text, lastPos, text.length(), result);

        return result.toArray(new String[result.size()]);

    }

    public static String[] splitByTags(final String text, String...tags) {
        // filter and process the tags.
        // remove null values, duplicates, empty strings, etc.
        return splitByTags(text, compileTags(Arrays.asList(tags)));
    }

    public static void main(String[] args) {
        String[][] tagSets = {
                {"china man", "beijing bell", "man eater"}

        };
        String[] inputs = {"China man eater Japan Beijing bell"};

        List&lt;CompiledTagSet&gt; compiled = Arrays.stream(tagSets).map(tags -&gt; compileTags(Arrays.asList(tags))).collect(Collectors.toList());

        for (String input : inputs) {
            for (CompiledTagSet ts : compiled) {
                System.out.printf("Split: %s%nUsing: %s%nMatch: %s",
                        input, ts, Arrays.toString(splitByTags(input, ts)));
            }
        }

    }
}


Note that there is special handling for situations where one tag is a prefix of another tag.

The above code produces the output:

Split: China man eater Japan Beijing bell
Using: [man eater, china man, beijing bell]
Match: [China man, eater Japan, Beijing bell]