不幸的是,我正在使用 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/