集合去重,可以使用Set不能添加重复元素的特性来实现,像下面这样
public class Test {
public static void main(String[] args) {
List<Car> cars = Arrays.asList(new Car("benz"), new Car("bmw"), new Car("bmw"));
Set<String> brands = new HashSet<>();
List<Car> che = new ArrayList<>();
cars.stream().forEach(car -> {
if (brands.add(car.getBrand())) {
che.add(car);
}
});
System.out.println(che);
}
}
class Car {
private String brand;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Car(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
'}';
}
}
也能使用函数式编程的加stream api的方式来实现
public class ListUtil {
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
cars.stream().filter(ListUtil.distinctByKey(Car::getBrand)).forEach(System.out::println);
先获取集合的stream流,再调用流的filter方法,filter的参数是个Predicate(断言型,Java8中的四大函数型接口之一)函数,使得断言型函数为true的元素会被保留下来。
distinctByKey函数中创建一个map,再调putIfAbsent方法,如果某元素不存在,putIfAbsent就返回null,整个断言型函数就返回true,当前遍历到的元素就会被保留下来