java8根据1.多个属性相同时去重 --2.属性大小比较去重

2023-05-16

public class Demo02If {
	public static void main(String[] args) {


		List<Person> personList = new ArrayList<>();
		personList.add(new Person("one", 10));
		personList.add(new Person("two", 20));
		personList.add(new Person("three", 30));
		//这两的name值重复
		personList.add(new Person("four", 40));
		personList.add(new Person("four", 45));
		personList.add(new Person("four", 45));

		System.out.println("利用Collectors.toMap去重:");
		//利用Collectors.toMap去重
		personList.stream()
				.collect(Collectors.toMap(Person::getName, Function.identity(), (oldValue, newValue) -> oldValue))
				.values()
				.stream()
				.forEach(System.out::println); //打印

		//根据name和age 相同时去重
		ArrayList<Person> collect = personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
				new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getAge()))), ArrayList::new));

		System.out.println(collect);
	}

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java8根据1.多个属性相同时去重 --2.属性大小比较去重 的相关文章

随机推荐