首页 > 解决方案 > 在 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 值是不同的。如何通过将空记录和空记录视为相同来实现在此处获取单个记录。

标签: javacollectors

解决方案


您可以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 = "";

这也可能是一个选择..


推荐阅读