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