Skip to content

Instantly share code, notes, and snippets.

@netstart
Created August 26, 2019 13:31
Show Gist options
  • Save netstart/9cba95081436dcdff052b19b7e3c4ab2 to your computer and use it in GitHub Desktop.
Save netstart/9cba95081436dcdff052b19b7e3c4ab2 to your computer and use it in GitHub Desktop.
public class CollectionUtil {
/**
* Distinct by multiple fields – distinctByKeys() function
*
* <PRE>
* List<Record> list = recordsList.stream()
* .filter(distinctByKeys(Record::getId, Record::getName))
* .collect(Collectors.toList());
* </PRE>
*
* @see https://howtodoinjava.com/java8/stream-distinct-by-multiple-fields/
*
* @param <T>
* @param keyExtractors
* @return
*/
public static <T> Predicate<T> distinctByKeys(Function<? super T, ?>... keyExtractors) {
final Map<List<?>, Boolean> seen = new ConcurrentHashMap<>();
return t -> {
final List<?> keys = Arrays.stream(keyExtractors).map(ke -> ke.apply(t)).collect(Collectors.toList());
return seen.putIfAbsent(keys, Boolean.TRUE) == null;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment