Using Java 8 new constructs such as threads, for example, is there a way to filter Set based on the order in another collection?
Set<Person> persons = new HashSet<>(); persons.add(new Person("A", 23)); persons.add(new Person("B", 27)); persons.add(new Person("C", 20)); List<String> names = new ArrayList<>(); names.add("B"); names.add("A");
I want to filter elements from the persons set based on names , so that only those who have their own names specified in names will be saved, but in the order they appear in names .
So i want
Set<Person> filteredPersons = ...;
where the 1st element is Person("B", 27) , and the second element is Person("A", 23) .
If I do the following,
Set<Person> filteredPersons = new HashSet<>(persons); filteredPersons = filteredPersons.stream().filter(p -> names.contains(p.getName())).collect(Collectors.toSet());
the order is not guaranteed to be the same as in names , if I'm not mistaken.
I know how to achieve this using a simple loop; I'm just looking for a way to use java 8.
Thanks for watching!
EDIT:
A for loop that achieves the same result:
Set<Person> filteredPersons = new LinkedHashSet<>(); for (String name : names) { for (Person person : persons) { if (person.getName().equalsIgnoreCase(name)) { filteredPersons.add(person); break; } } }
The implementation of LinkedHashSet ensures that order is maintained.
source share