Concat strings in Java
Here is what it looks like you're trying to do:


loop through set, loop through each individual word in set, until you find toMerge.
When you find that, you then restart the loop through set, and each word in set until you find fromMerge.


This is producing a redundancy in the case that your initial loop iterates over fromMerge, but continues the loop because it is only looking for toMerge. The approach I would take to improve it would be to search for both in the same loop, thereby eliminating the redundant second loop.

public void find(ArrayList&lt;String&gt; operations, ArrayList&lt;String&gt; set) {
    String toMerge = operations.get(1);
    String fromMerge = operations.get(2);
    int toMergeIndex = -1, fromMergeIndex = -1; //add search indexes
    for (int i = 0; i &lt; set.size(); i++) {
        if (set.get(i).indexOf(toMerge) &gt; -1)
            toMergeIndex = i;
        if (set.get(i).indexOf(fromMerge) &gt; -1)
            fromMergeIndex = i;
        if (toMergeIndex != -1 &amp;&amp; fromMergeIndex != -1)
            break;
    if (toMergeIndex == -1 || fromMergeIndex == -1){
        throw new Exception();//Failed, didn't find. Deal with as you wish   
    }
    else{
        set.get(fromMergeIndex) += " " + set.get(toMergeIndex);
        set.get(toMergeIndex) = " ";
    }


This is the only efficiency improvement that I can think of. Hope it helps!