List对象属性去重JDK8

一:javabean如下,

public class Student {
	String name;
	int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Student() {
		super();
	}
}

二:方法如下,

	public static void main(String[] args) {
		Student p1 = new Student("lisi", 11);
		Student p2 = new Student("lishishi", 11);
		Student p3 = new Student("lisi", 11);

		List<Student> persons = Arrays.asList(p1, p2, p3);
		List<Student> unique = persons.stream().collect(Collectors.collectingAndThen(
				Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
		unique.forEach(p -> System.out.println(p));
	}

 三:运行结果如下,

发布了125 篇原创文章 · 获赞 27 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/weixin_39428938/article/details/90448271
今日推荐