【发布时间】:2020-10-15 19:59:30
【问题描述】:
我有 2 节课 Istaff 和 IstaffZone
public class Istaff {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String location;
private String community;
private String firstName;
private String lastName;
private String login;
private String locationID;
[...]
}
public class IstaffZone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String login;
private String locationID;
[...]
}
还有一组 Istaff,我想将其转换为一组 distinct IstaffZone 并仅获取不同的值。
我试图做类似...但结果值不明显
Set<IstaffZone> lStaffZones = new HashSet<IstaffZone>();
lStaffZones = listStaffT.stream().map(p ->
new IstaffZone( p.getLogin(),p.getLocationID()) )
.distinct()
.collect(Collectors.toCollection(HashSet::new));
或
List<IstaffZone> lStaffZones = new ArrayList<IstaffZone>();
lStaffZones = listStaffT.stream().map(p ->
new IstaffZone( p.getLogin(),p.getLocationID()) )
.distinct()
.collect(Collectors.toList());
有什么建议吗?
【问题讨论】:
-
您是否正确实施了
equals和hashCode? -
@Polygnome 否。如何正确实现 hashCode? Set 还是 List 更好?
-
List替换一个动态大小的索引数组,允许重复。Set仅保留唯一元素,其HashSet实现需要正确的hashCode和equals实现。这是一篇不错的文章开头:dzone.com/articles/working-with-hashcode-and-equals-in-java
标签: dictionary java-stream distinct