【问题标题】:Java 8 stream transform a set of many fields in a small set with distinct valuesJava 8 流转换一组具有不同值的小集合中的许多字段
【发布时间】:2020-10-15 19:59:30
【问题描述】:

我有 2 节课 IstaffIstaffZone

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());

有什么建议吗?

【问题讨论】:

  • 您是否正确实施了equalshashCode
  • @Polygnome 否。如何正确实现 hashCode? Set 还是 List 更好?
  • List 替换一个动态大小的索引数组,允许重复。 Set 仅保留唯一元素,其 HashSet 实现需要正确的 hashCodeequals 实现。这是一篇不错的文章开头:dzone.com/articles/working-with-hashcode-and-equals-in-java

标签: dictionary java-stream distinct


【解决方案1】:

如果您需要能够根据具体情况进行区分,或者您可能不想有一天实现哈希码,您也可以使用以下方法。使用此方法,您可以根据具体情况选择单个字段/多个字段用作键/哈希码,还可以在不同的碰撞中选择您想要的对象。

List<IstaffZone> lStaffZones = new ArrayList(listStaffT.stream()
             .map(p -> new IstaffZone( p.getLogin(),p.getLocationID()) )
             .collect(Collectors.toMap(
                       (iStaffZone) -> {
                            // return a key/hashcode that will be unique
                            // if it's just a single field, just return the field
                            return iStaffZone.getLogin + iStaffZone.getLocationID();
                       },
                       i -> i, //or Function.identity()
                       (iStaffZone1, iStaffZone2) -> x == null ? y : x)) 
                       // if iStaffZone1 and iStaffZone2 or the same, pick which gets saved
             .values());
// Collectors.toMap(a -> return key, b -> return value, (a,b) -> return element to save if same)

【讨论】:

    猜你喜欢
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多