方法一:
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SampleSupplierEntity {
// ... 省略其他代码
private String supplierName;
// ... 省略其他代码
public String getSupplierName() {
return supplierName;
}
// ... 省略其他代码
}
public class Main {
public static void main(String[] args) {
List<SampleSupplierEntity> sampleSupplierList = ...; // 初始化待去重的列表
Set<String> supplierNameSet = new HashSet<>(); // 使用 Set 集合去重
List<SampleSupplierEntity> resultList = new ArrayList<>(); // 用于存储去重后的结果
// 遍历待去重的列表
for (SampleSupplierEntity sampleSupplier : sampleSupplierList) {
// 获取供应商名称
String supplierName = sampleSupplier.getSupplierName();
// 如果 Set 集合中不包含该供应商名称,则添加到结果列表中
if (!supplierNameSet.contains(supplierName)) {
supplierNameSet.add(supplierName);
resultList.add(sampleSupplier);
}
}
// 去重完成,结果列表存储的是去重后的数据
System.out.println(resultList);
}
}
在上面的代码中,我们使用了一个 HashSet 来存储不重复的名字,并在循环中判断每个元素的名字是否已经存在,如果不存在,就将其加入到结果列表中。这样,我们就实现了基于名字字段的去重。
方法二:
List<SampleSupplierEntity> uniqueList = sampleSupplierList.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName()))), ArrayList::new)
);
这个代码使用了Stream API和Collectors类,以便对列表进行转换和重构。首先,我们将列表转换为流,然后使用collectingAndThen方法来计算结果:
首先,我们使用toCollection方法创建一个新的树集,它使用了比较器,以便在放置元素时对名称进行比较。这样,树集就保证了元素的唯一性。
然后,我们使用ArrayList::new将树集转换回列表,以便在最后使用列表。
现在,您可以使用uniqueList变量访问去重后的列表,其中名称是唯一的。