import lombok.Data;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* 根据对象的某一个属性进行去重
*/
@Data
public class Test {
private String id;
private String name;
private Integer age;
public Test(String id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public static void main(String[] args) {
ArrayList<Test> list1 = new ArrayList<>();
list1.add(new Test("1", "A", 1));
list1.add(new Test("2", "B", 2));
list1.add(new Test("3", "C", 3));
list1.add(new Test("4", "D", 4));
ArrayList<Test> list2 = new ArrayList<>();
list2.add(new Test("1", "E", 5));
list2.add(new Test("4", "F", 6));
list1.addAll(list2);
ArrayList<Test> collect = list1.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<Test>(Comparator.comparing(Test::getId))), ArrayList::new));
collect.forEach(System.out::println);
}
}
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 并集
*/
@Data
public class Test {
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<>();
list1.add("1");
list1.add("2");
list1.add("3");
list1.add("4");
ArrayList<String> list2 = new ArrayList<>();
list2.add("1");
list2.add("2");
list2.add("3");
list2.add("4");
list2.add("5");
list2.add("6");
list1.addAll(list2);
List<String> collect = list1.stream().distinct().collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 交集
*/
@Data
public class Test {
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<>();
list1.add("1");
list1.add("2");
list1.add("3");
list1.add("4");
ArrayList<String> list2 = new ArrayList<>();
list2.add("1");
list2.add("2");
list2.add("3");
list2.add("4");
list2.add("5");
list2.add("6");
List<String> collect = list1.stream().filter(s -> list2.contains(s)).collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
网友评论