List is de-duplicated according to an attribute of an object
public class Test {
public static void main(String[] args) {
List<User> list = new Lists.newArrayList();
list.add(new user(1,"Zhang San", "ShangHai"));
list.add(new user(2, "Li Si", "Beijing"));
list.add(new user(3, "Wang Wu", "Jinan"));
list.add(new user(4, "Li Si", "Beijing"));
// de-duplicate the list according to the city in the list
newList = list.stream().filter(distinctByKey(User::getCity)).collect(Collectors.toList());
}
private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
Read More:
- JAVA 8: How to Convert List to Map
- [Solved] Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]
- [Solved] Failed toString() invocation on an object com.alibaba.fastjson.JSONException: write javaBean error
- How to Check the appPackage or appActivity of an APK
- [Solved] POI Read excel Error: Your InputStream was neither an OLE2 stream, nor an OOXML stream
- [Solved] stream Convert list to map Error: java.lang.IllegalStateException: Duplicate key
- Java will convert Excel to list set or JSON, export excel file to local, excel import and export, easyexcel tool class
- [Solved] Failed to instantiate java.util.List using constructor NO_CONSTRUCTOR with arguments
- [Solved] Springboot Project Start Error: An attempt was made to call the method com.google.common.collect.Multimaps.asMap
- Springboot reports an error After adding the import annotation: application failed to start
- Java Error: No enclosing instance of type Main is accessible. Must qualify the allocation with an encl
- [Solved] Error installing MVN: Java_Home is set to an invalid directory
- How to Solve Image Upload Error: Uncaught (in promise) DOMException: Failed to execute ‘put‘ on ‘IDBObjectStore‘
- [Solved] Error getting generated key or setting result to parameter object. UnsupportedOperationException
- The node requests the API address written by java to report an error error:getaddrinfo ENOTFOUND
- [Solved] Pycharm Failed to Upload: Upload to *** failed. Could not list the contents of folder “sftp
- How to convert a Java string into a number (stringtonumber)
- Redis: How to Implementate LRU Caching Mechanism Manually
- [Solved] Java.lang.ClassCastException: [Ljava.lang.Long; cannot be cast to java.util.List
- OpenFeignClient Use Object to Receive text/plain Type Return Error