在Java 8中,如何Stream通过检查每个对象的属性的清晰度来使用API 过滤集合?
例如,我有一个Person对象列表,我想删除具有相同名称的人,
persons.stream().distinct();
Run Code Online (Sandbox Code Playgroud)
将使用Person对象的默认相等检查,所以我需要像,
persons.stream().distinct(p -> p.getName());
Run Code Online (Sandbox Code Playgroud)
不幸的是,该distinct()方法没有这种过载.如果不修改类中的相等性检查,Person是否可以简洁地执行此操作?
我试图基于某些属性从对象列表中删除重复项.
我们可以使用java 8以简单的方式完成它
List<Employee> employee
Run Code Online (Sandbox Code Playgroud)
我们可以根据id员工的财产从中删除重复项.我已经看到帖子从字符串的arraylist中删除重复的字符串.
我试图使用Java 8流来组合列表.如何从两个现有列表中获取"对称差异列表"(仅存在于一个列表中的所有对象).我知道如何获得交叉列表以及如何获取联合列表.
在下面的代码中,我想要来自两个汽车列表(bigCarList,smallCarList)的不相交的汽车.我希望结果能够列出2辆车("丰田卡罗拉"和"福特福克斯")
示例代码:
public void testDisjointLists() {
List<Car> bigCarList = get5DefaultCars();
List<Car> smallCarList = get3DefaultCars();
//Get cars that exists in both lists
List<Car> intersect = bigCarList.stream().filter(smallCarList::contains).collect(Collectors.toList());
//Get all cars in both list as one list
List<Car> union = Stream.concat(bigCarList.stream(), smallCarList.stream()).distinct().collect(Collectors.toList());
//Get all cars that only exist in one list
//List<Car> disjoint = ???
}
public List<Car> get5DefaultCars() {
List<Car> cars = get3DefaultCars();
cars.add(new Car("Toyota Corolla", 2008));
cars.add(new Car("Ford Focus", 2010));
return cars;
}
public List<Car> get3DefaultCars() {
List<Car> cars …Run Code Online (Sandbox Code Playgroud)