java - 在 Collectors.groupingBy 中考虑 null 和空记录相同
问题描述
我有一个对象列表,其中一些记录可以具有空值属性,而一些记录可以具有空值属性。使用 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
编辑:您还可以考虑将类型初始化为空 String 而不是null
,那么您不需要修改任何内容:
private String type = "";
这也可能是一个选择..
推荐阅读
- string - 在 Lua 中使用新行时遇到问题
- esp8266 - 我可以将 esp8266 SPI 与 ds1302 一起使用吗
- r - 对由其他列表组成的列表进行排序
- git - 在不重新创建提交的情况下调整先前的提交
- c++ - 在场景中近似具有多个已知长度的车辆的速度
- bash - 为什么`cd`会破坏`exec`的重定向?
- vba - API 声明 PtrSave - 类型不匹配
- android - gradle 无法解析房间版本 2.3.0
- machine-learning - 如何将两个 tflite 模型组合成一个 tflite 模型以创建图像分类 android 应用程序
- python - 基于Nan或另一列中的布尔值的Python Shift值在一列中