java - 如何从多值映射中删除 "vertical duplicate"值?

标签 java dictionary data-structures

不幸的是,我正在使用 Java 中的一些不太令人满意的数据结构,并且我的任务是删除多值映射 ( Map<Enum, List<String>> ) 中的“垂直重复项”,其中所有值 ( List<String> ) 大小相同

以下是我的意思的示例:

{
    // Column : 1    2    3    4    5    6    7    8    9
    NUMBER : [ "1", "2", "3", "1", "2", "3", "1", "2", "3" ],
    LETTER : [ "A", "B", "C", "A", "E", "F", "G", "B", "I" ],
    SYMBOL : [ "!", "!", "!", "!", "!", "!", "!", "!", "!" ],
    ...
}

“垂直重复”是与任何先前列具有相同值的任何列。在上面的 map 中,重复项将是列 [1,4] (均具有值 1,A,! )和 [2,8] (均具有值 2,B,! )。

删除“垂直重复项”后上述 map 的输出:

{
    // Previous Column:
    //          1    2    3    5    6    7    9
    NUMBER : [ "1", "2", "3", "2", "3", "1", "3" ],
    LETTER : [ "A", "B", "C", "E", "F", "G", "I" ],
    SYMBOL : [ "!", "!", "!", "!", "!", "!", "!" ],
    ...
}

有没有一种简单的方法可以删除“垂直重复项”?我正在使用具有不同键集大小的多值映射(一个映射可能有 3 个不同的枚举键,另一个映射可能有 17 个不同的枚举键),以及不同的值集大小(一个映射可能包含每个列表大小为 2,另一个可能包含每个大小为 20 的列表。

最佳答案

我建议对这些数据使用基于列的数据结构,而不是基于行的数据结构。至少您可以/应该使用这样的结构来执行此操作,并且您可以添加一个简单的方法来将其返回到行式多重映射。这是一个完整功能示例的样子:

public enum Row {
    NUMBER, LETTER, SYMBOL, WHATEVER1, WHATEVER2
}

public static class Col {
    Map<Row, String> col = new HashMap<>();

    public Col(Entry<Row, String>... entries) {
        for (Entry<Row, String> entry: entries) {
            col.put(entry.getKey(), entry.getValue());
        }
    }

    // to use within a LinkedHashSet
    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (other == null || getClass() != other.getClass()) return false;
        return Objects.equals(col, ((Col) other).col);
    }

    @Override
    public int hashCode() { return Objects.hash(col); }

    @Override
    public String toString() { return col.toString(); }
}


public static void main(String[] argv) {
    // alternatively use LinkedHashSet directly
    List<Col> cols = new ArrayList<>();
    cols.add(new Col(new SimpleEntry<>(Row.NUMBER, "1"), new SimpleEntry<>(Row.LETTER, "A"), new SimpleEntry<>(Row.WHATEVER1, "X")));
    cols.add(new Col(new SimpleEntry<>(Row.NUMBER, "2"), new SimpleEntry<>(Row.LETTER, "B"), new SimpleEntry<>(Row.SYMBOL, "!")));
    cols.add(new Col(new SimpleEntry<>(Row.NUMBER, "1"), new SimpleEntry<>(Row.LETTER, "A"), new SimpleEntry<>(Row.WHATEVER1, "X")));

    // turn original structure unique keeping order of insertion
    Set<Col> unique = new LinkedHashSet<>(cols);

    System.out.println(unique);
}

打印

[{LETTER=A, NUMBER=1, WHATEVER1=X}, {LETTER=B, NUMBER=2, SYMBOL=!}]

关于java - 如何从多值映射中删除 "vertical duplicate"值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49088044/

相关文章:

java - LCP如何帮助查找模式的出现次数?

java - 在处理数据之前强制 JDialog 可见?

python - 如何将字典中的列表元素相乘

python - 将带有 Numpy Nd-Array 值的 python 字典写入 Json 文件的有效方法

c++ - 选择合适的数据结构

algorithm - 如何提高关键字搜索的性能?

java - 如何在ubuntu中从命令行制作jar文件

Java 字符串导入 java.lang.String

java - 无法在主方法中引用我的方法,出现编译错误

.net - 字典与 KeyPairValue 的使用