业务场景
需要把A集合中的B集合不包含的元素取出
需要把A、B集合中的都包含的元素取出
实体类
package com.wfw.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
1. @Description
2. @Author wfw
3. @Date 2021/10/8 15:19
*/
@ConfigurationProperties(prefix = "car")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
private Integer id;
private String name;
private Integer money;
}
测试类
先创建两个集合
List<Car> one=new ArrayList<>();
one.add(new Car(1,"比亚迪",100));
one.add(new Car(2,"奔驰",1000));
one.add(new Car(3,"奥迪",2000));
List<Car> two=new ArrayList<>();
two.add(new Car(4,"领克03+",1000));
two.add(new Car(5,"五菱宏光",100));
two.add(new Car(3,"奥迪",2000));
two.add(new Car(2,"奔驰",1000));
打印两个集合
可以知道one中的比亚迪是two中不包含的,比较是通过他们的唯一标识来区分的即:id
筛选代码
package com.wfw;
import com.wfw.entity.Car;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Description
* @Author wfw
* @Date 2021/10/9 9:26
*/
public class TestMain {
public static void main(String[] args) {
List<Car> one=new ArrayList<>();
one.add(new Car(1,"比亚迪",100));
one.add(new Car(2,"奔驰",1000));
one.add(new Car(3,"奥迪",2000));
List<Car> two=new ArrayList<>();
two.add(new Car(4,"领克03+",1000));
two.add(new Car(5,"五菱宏光",100));
two.add(new Car(3,"奥迪",2000));
two.add(new Car(2,"奔驰",1000));
System.out.println("one:"+one);
System.out.println("two:"+two);
List<Integer> tIds = two.stream().map(Car::getId).collect(Collectors.toList());//two集合中所有car的id集合
List<Car> ones = one.stream().filter(o -> !tIds.contains(o.getId())).collect(Collectors.toList());//取出one中car的id在two中不被包含的元素集合
System.out.println("one中不被two包含的元素:" + ones);
}
}
结果
同样如果想获取one中在two也同时包含的元素时只需要把判断条件中的
filter(o -> !tIds.contains(o.getId()))
改为:**!**去掉即可
filter(o -> tIds.contains(o.getId()))
测试结果
如果有问题希望大神指教,小白一枚。如果又更好的办法希望评论留下互相学习。