Skip to content

Commit

Permalink
list对象根据属性去重 lambda + stream
Browse files Browse the repository at this point in the history
  • Loading branch information
hisenyuan committed Apr 19, 2018
1 parent 625394f commit 17c3181
Showing 1 changed file with 7 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.alibaba.rocketmq.shade.com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
Expand Down Expand Up @@ -38,14 +37,18 @@ public static void main(String[] args) {
}

/**
*
* 过滤方法
* @param keyExtractor
* @param <T>
* @return
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>(16);
return t -> map.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE) == null;

// 这个也可以,不过感觉效率要低一些,线程不是那么安全
// Set<Object> seen = ConcurrentHashMap.newKeySet();
// return t -> seen.add(keyExtractor.apply(t));
}

/**
Expand Down

0 comments on commit 17c3181

Please sign in to comment.