Skip to content

Instantly share code, notes, and snippets.

@liviutudor
Created April 1, 2017 00:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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