Skip to content

Instantly share code, notes, and snippets.

@codethereforam
Created January 13, 2019 07:57
Show Gist options
  • Save codethereforam/5bd47c6b6765c40431c7ae6172c8f4c0 to your computer and use it in GitHub Desktop.
Save codethereforam/5bd47c6b6765c40431c7ae6172c8f4c0 to your computer and use it in GitHub Desktop.
Java 8 Distinct by property
public class StreamUtil {
private StreamUtil() {
}
/**
* stream Distinct by property
*
* @param keyExtractor keyExtractor
* @return java.util.function.Predicate<T>
* @author yanganyu
* @date 2018/10/15 17:37
* @see <a href="https://stackoverflow.com/questions/23699371/java-8-distinct-by-property">Java 8 Distinct by property</a>
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment