我有一个对象列表,其中一些记录可以具有空值属性,一些记录可以具有空值属性。使用 Collectors.groupingBy 我需要将两条记录视为相同。
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Code {
private String type;
private String description;
public static void main(String[] args) {
List<Code> codeList = new ArrayList<>();
Code c = new Code();
c.setDescription("abc");
c.setType("");
codeList.add(c);
Code c1 = new Code();
c1.setDescription("abc");
c1.setType(null);
codeList.add(c1);
Map<String, List<Code>> codeMap = codeList.stream()
.collect(Collectors.groupingBy(code -> getGroupingKey(code)));
System.out.println(codeMap);
System.out.println(codeMap.size());
}
private static String getGroupingKey(Code code) {
return code.getDescription() +
"~" + code.getType();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
codeMap 的结果将有两条记录,因为它认为 Type 属性中的空字符串和 null 值不同。如何通过将空记录和空记录视为相同来实现在此处获取单个记录。
最佳答案
您可以像这样修改您的 getGroupingKey
方法:
private static String getGroupingKey(Code code) {
return code.getDescription() + "~" + (code.getType() == null ? "" : code.getType());
}
或者像这样:
private static String getGroupingKey(Code code) {
return code.getDescription() + "~" + Optional.ofNullable(code.getType()).orElse("");
}
或者您也可以直接修改您的 getType()
方法,如下所示:
public String getType() {
return type == null ? "" : type;
}
或者:
public String getType() {
return Optional.ofNullable(type).orElse("");
}
两者的工作原理应该是相同的。我想根据您的要求选择一个..
如果将以下 toString
方法添加到您的 Code
类中:
@Override
public String toString() {
return "Code{" +
"type='" + type + '\'' +
", description='" + description + '\'' +
'}';
}
.. 使用修改后的 getGroupingKey
方法(或 getType
方法),输出应如下所示:
{abc~=[Code{type='', description='abc'}, Code{type='null', description='abc'}]}
1
编辑:您还可以考虑将类型初始化为空字符串而不是 null
,这样您就不需要修改任何内容:
private String type = "";
这也可能是一个选择..
关于java - 在 Collectors.groupingBy 中将 null 和空记录视为相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53440190/