Skip to content

Instantly share code, notes, and snippets.

@liviutudor
Created April 1, 2017 00:37
Show Gist options
  • Save liviutudor/ed03abd77367bf594e57cbcdc342d9d7 to your computer and use it in GitHub Desktop.
Save liviutudor/ed03abd77367bf594e57cbcdc342d9d7 to your computer and use it in GitHub Desktop.
Find element in a collection in java using streams
// this returns a list
public Collection<Employee> findName(Collection<Employee> collection, String name) {
return collection.stream().filter(e -> e.firstName.equals(name)).collect(Collectors.toList());
}
// if we want to return a set (and therefore guarantee uniqueness)
public Collection<Employee> findName(Collection<Employee> collection, String name) {
return collection.stream().filter(e -> e.firstName.equals(name)).collect(Collectors.toList());
}
// or if we want to use a specialized collection class
public Collection<Employee> findName(Collection<Employee> collection, String name) {
return collection.stream().filter(e -> e.firstName.equals(name)).collect(Collectors.toCollection(() -> new LinkedBlockingQueue<>()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment