Created
April 1, 2017 00:37
-
-
Save liviutudor/ed03abd77367bf594e57cbcdc342d9d7 to your computer and use it in GitHub Desktop.
Find element in a collection in java using streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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