java - 在 Collectors.groupingBy 中将 null 和空记录视为相同

标签 java collectors

我有一个对象列表,其中一些记录可以具有空值属性,一些记录可以具有空值属性。使用 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/

相关文章:

java - JDBC数据库访问、插入元组

java - 我可以监视使用 get 方法的对象吗?

java - 如何获取引用单元格范围的 Excel 数据验证下拉值

Java 8 lambdas 按多个字段分组

java - 使用流收集返回相同的列表,对重复项进行切割和求和,抛出非静态引用

dictionary - 如何使用Java 8中的方法引用进行Map合并?

java - 以这种方式构造对象是否不符合常规? (关于同一个构造函数的几个问题)

java - 流迭代不使用最后一个值

java - 将一组 map 流式传输到单个 map 中

java - collectingAndThen方法足够高效吗?