基于Java8, 去除List中对象重复,不多说,直接上代码。
public class TestDemo {
class Ab {
private Long id;
private String name;
public Ab() {
}
public Ab(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 boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Ab ab = (Ab) o;
if (!id.equals(ab.id))
return false;
return name.equals(ab.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 100 * result + name.hashCode();
return result;
}
}
public static void main(String[] args) {
TestDemo t = new TestDemo();
List<Ab> l1 = Arrays.asList(t.new Ab(1l, "a"), t.new Ab(2l, "b"));
List<Ab> l2 = Arrays.asList(t.new Ab(1l, "a"), t.new Ab(3l, "b"));
List<Ab> list = new ArrayList<TestDemo.Ab>();
list.addAll(l1);
list.addAll(l2);
List<Ab> unique = list.stream().distinct().collect(Collectors.toList());
System.out.println(JsonUtils.toJson(unique));
}
}