Created
August 26, 2019 13:31
-
-
Save netstart/9cba95081436dcdff052b19b7e3c4ab2 to your computer and use it in GitHub Desktop.
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
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