如何去重复

public class test {
private Long id;
private String name;
}

id=“123456” name=“tt”
id=“1234562” name=“tt”
id=“123456” name=“tt”
id=“123456” name=“tt”

最后得到的list里面是有2个对象
根据id去重,只保留一个重复

import java.util.*;
import java.util.stream.Collectors;

class Test {
	private Long id;
	private String name;

	public Test(Long id, String name) {
		this.id = id;
		this.name = name;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Test{" +
				"id=" + id +
				", name='" + name + '\'' +
				'}';
	}
}

public class Demo {
	public static void main(String[] args) {
		List<Test> tests = new ArrayList<>();
		tests.add(new Test(1L,"1"));
		tests.add(new Test(2L,"1"));
		tests.add(new Test(3L,"1"));
		tests.add(new Test(1L,"2"));
		tests.add(new Test(2L,"3"));
		tests.add(new Test(3L,"4"));

		tests = removeDuplicate(tests);
		tests.stream().forEach(System.out::println);
	}

	public static List<Test> removeDuplicate(Collection<Test> collection){
		Map<Long,Test> map = new HashMap<>();
		for(Test test : collection){
			map.put(test.getId(),test);
		}
		return map.values().stream().collect(Collectors.toList());
	}
}

1 Like

重写 equals 和 hashCode,先放到Set里,再放到list

1 Like