3 回答
TA贡献1816条经验 获得超6个赞
首先像这样覆盖equals和hashCode方法MyClass,
@Override
public int hashCode() {
return 31 * s1.hashCode() + s2.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof MyClass && ((MyClass) obj).getS1().equals(getS1())
&& ((MyClass) obj).getS2().equals(getS2());
}
那么消除重复的最简单方法是使用Set.
new HashSet<>(instances)
TA贡献1830条经验 获得超9个赞
实现 hashcode() 或 equals() 不是必须的。这是一种方法:
Map<List<String>, MyClass> map = new HashMap<>();
List<MyClass> distinctList = myCollection.stream()
.collect(Collectors.toMap(c -> Arrays.asList(c.s1, c.s2), Function.identity(), (x,y)->x))
.values()
.stream()
.collect(Collectors.toList());
TA贡献1942条经验 获得超3个赞
您需要覆盖equal和hash code函数,然后使用java 8的Streaming API的distinct函数。
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class MyClass {
private String s1;
private String s2;
public MyClass() {
}
public MyClass(String s1, String s2) {
this.s1 = s1;
this.s2 = s2;
}
public String getS1() {
return s1;
}
public MyClass setS1(String s1) {
this.s1 = s1;
return this;
}
public String getS2() {
return s2;
}
public MyClass setS2(String s2) {
this.s2 = s2;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MyClass myClass = (MyClass) o;
return Objects.equals(getS1(), myClass.getS1()) &&
Objects.equals(getS2(), myClass.getS2());
}
@Override
public int hashCode() {
return Objects.hash(getS1(), getS2());
}
@Override
public String toString() {
return "MyClass{" + "s1='" + s1 + '\'' + ", s2='" + s2 + '\'' + '}';
}
public static void main(String[] args) {
List<MyClass> list = new ArrayList<>();
list.add(new MyClass("a", "b"));
list.add(new MyClass("a", "c"));
list.add(new MyClass("a", "b"));
list.add(new MyClass("a", "d"));
System.out.println("Original size is : " + list.size()); // Size is 4
list.forEach(System.out::println);
//Now remove duplicate
List<MyClass> expected = list.stream().distinct().collect(Collectors.toList());
System.out.println(
"After remove duplication size is : " + expected.size()); // Here is your expected result size is 3
expected.forEach(System.out::println);
}
}
这是输出:
原尺寸为:4
我的类{s1='a', s2='b'}
我的类{s1='a', s2='c'}
我的类{s1='a', s2='b'}
我的类{s1='a', s2='d'}
删除重复后大小为:3
我的类{s1='a', s2='b'}
我的类{s1='a', s2='c'}
我的类{s1='a', s2='d'}
添加回答
举报