Java 8 Filter set based on another set
<p><em>Using Java 8 new constructs</em>, such as streams for example, is there a way to filter a <code>Set</code> based on the order in another collection?</p>

<pre><code>Set&lt;Person&gt; persons = new HashSet&lt;&gt;();

persons.add(new Person("A", 23));
persons.add(new Person("B", 27));
persons.add(new Person("C", 20));

List&lt;String&gt; names = new ArrayList&lt;&gt;();
names.add("B");
names.add("A");
</code></pre>

<p>I want to filter items from set <code>persons</code> based on <code>names</code>, such that only those persons who have their names specified in <code>names</code> will be retained, but in the order that they appear in <code>names</code>.</p>

<p>So, I want</p>

<pre><code>Set&lt;Person&gt; filteredPersons = ...;
</code></pre>

<p>where 1st element is <code>Person("B", 27)</code> and 2nd element is <code>Person("A", 23)</code>.</p>

<p>If I do the following,</p>

<pre><code>Set&lt;Person&gt; filteredPersons = new HashSet&lt;&gt;(persons);
filteredPersons = filteredPersons.stream().filter(p -&gt; names.contains(p.getName())).collect(Collectors.toSet());
</code></pre>

<p>the order is not guaranteed to be the same as in <code>names</code>, if I am not mistaken.</p>

<p>I know how to achieve this using a simple <em>for</em> loop; I'm just looking for a java 8 way of doing it.</p>

<p>Thanks for looking!</p>

<p><strong>EDIT:</strong></p>

<p>The <em>for</em> loop that achieves the same result:</p>

<pre><code>Set&lt;Person&gt; filteredPersons = new LinkedHashSet&lt;&gt;();
for (String name : names) {
  for (Person person : persons) {
    if (person.getName().equalsIgnoreCase(name)) {
      filteredPersons.add(person);
      break;
    }
  }
}
</code></pre>

<p>The <code>LinkedHashSet</code> implementation ensures that the order is maintained.</p>