Java 8的Hashmap | Lombok的@Data | 在Collectors.groupingBy中方法不可读取 | 复合键

huangapple go评论122阅读模式
英文:

Java 8 Hashmap | Lombok @Data | Method not readable in Collectors.groupingBy | Composite Key

问题

以下是使用Lombok的@Data注解的bean示例:

@Data
public class XxedgeCrtV implements Serializable {

    private static final long serialVersionUID = 1L;

    private String registryId;
    private String personPartyId;
    private String source;

    private String compositeKey() {
        return registryId + personPartyId + source;
    }
}

当我尝试在复合键上使用Java 8创建哈希映射时,它不会读取该方法:

Set<String> duplicates = xxedgeCrtVList.stream()
    .collect(Collectors.groupingBy(XxedgeCrtV::compositeKey, Collectors.counting()))
    .entrySet().stream()
    .filter(e -> e.getValue() > 1L)
    .map(e -> e.getKey())
    .collect(Collectors.toSet());

有人可以建议如何让代码读取这个方法吗?

我正在将复合键作为键,因为我必须在列表中搜索重复项。

英文:

The following is a bean in use having lombok @Data annotation:

@Data
public class XxedgeCrtV implements Serializable {
	
	private static final long serialVersionUID = 1L;

    private String registryId;
    private String personPartyId; 
    private String source;
	
    private String compositeKey() {
    	return registryId + personPartyId + source;
    }
}

When I tried to use create hashmap using Java 8 on composite key then it does not read the method:

Set&lt;String&gt; duplicates  = xxedgeCrtVList.stream()
    .collect(Collectors.groupingBy(XxedgeCrtV::compositeKey, Collectors.counting()))
    .entrySet().stream()
				.filter(e -&gt; e.getValue() &gt; 1L)
				.map(e -&gt; e.getKey())
				.collect(Collectors.toSet());

Can anyone suggest how to get code read this method?

I am making key of composite keys as I have to search for duplicates in list.

答案1

得分: 0

以下是翻译后的内容:

方法引用和 Lombok 插件都没有错误。分组的返回类型是一个 Map

Map<String, Long> duplicates = xxedgeCrtVList.stream()
    .collect(Collectors.groupingBy(XxedgeCrtV::compositeKey, Collectors.counting()));

使用这段代码,我没有获得编译错误。

我认为这是 IDE 的问题,应该对返回类型提出警告,而不是对方法引用提出警告。可能还有其他问题:

  • 如果 XxedgeCrtV 是内部类,应该声明为 static
  • 如果 XxedgeCrtV 在不同的文件中,compositeKey 的可见性不应为 private
英文:

There is neither an error in the method reference nor the Lombok plugin. The return type of grouping is a Map:

Map&lt;String, Long&gt; duplicates  = xxedgeCrtVList.stream()
    .collect(Collectors.groupingBy(XxedgeCrtV::compositeKey, Collectors.counting()));

With this code, I get no compilation error.

I bet this is the IDE issue that should complain about the return type rather than the method reference. There might be also different issue, if so:

  • The class XxedgeCrtV if inner shall be static.
  • The visibility of the compositeKey should not be private if XxedgeCrtV is in a different file.

huangapple
  • 本文由 发表于 2020年10月14日 15:53:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64348893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定