java8里面有个distinct()方法其实也能去重,但是需要重写equals()方法和hashcode()方法,具体如何写有很多例子就不多说了。我觉得不是很简便,找到一个新的酷炫plus的方法,在此记录一下,以便日后好查找。
代码如下:
List<StaffResponse> newList = staffResponseList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparing(StaffResponse::getId))), ArrayList::new)); 其中collectingAndThen 和 toCollection 都是 Collectors的方法, comparing是Comparator的方法,如果你的比较的属性是其他类型的,可将comparing替换成comparingLong等