检查两个列表的交集是否有效,不需要返回交集本身



我有两个列表(List1和List2),其中包含Column类型的对象。列有两个私有变量-名称和类型。List1和List2的交集由Column的名称完成。例如:

List1 = { Column (name = "A", type = "STRING"), Column (name = "B", type = "INT") }
List2 = { Column (name = "A", type = "STRING"), Column (name = "D", type = "INT") } 

则List1和List2的交集={Column(name="A",type="STRING")}

如何在Java 8中高效地编写代码,而不使用双for循环(O(n^2))来检查交集是否有效(如果它无效,那么我想知道列名以及冲突的类型,如果它有效,只返回True就足够了-我不需要交集本身)。一个有效的交集定义如下:通过比较字段名称完成的交集中的列必须具有相同的类型。例如,以下内容无效:

List1 = { Column (name = "A", type = "STRING"), Column (name = "B", type = "INT") }
List2 = { Column (name = "A", type = "INT"), Column (name = "D", type = "INT") } 

则List1和List2的无效交集={Column(name="A",type="STRING")}因为类型不匹配。另一种思考方式是给定List1中的列列表和List2中的列列表,我想检查List1和List2中的列是否具有相同的类型。

第一次尝试:

 for (final Column newColumn : newMySQLTableMetaData.getColumns()) {
            for (final Column originalColumn : originalMySQLTableMetaData.getColumns()) {
                if (newColumn.getName().equals(originalColumn.getName())) {
                    if (!newColumn.getType().equals(ColumnTypeConverter.toLogicalColumnType(originalColumn.getType()))) {
                        throw new UploadException("The column types have a mismatch. Original column" +
                                " named " + originalColumn.getName() + " a type of " + originalColumn.getType().toString() + " " +
                                "while new column with the same name has a type of " + newColumn.getType().toString());
                    }
                }
            }
        }

通过namelist1中的所有元素放入HashMap索引中。抛出第二个列表,看看第一个列表中是否有匹配的列(每个元素O(1))。如果是,请检查是否存在冲突。

private List<String> conflictList = new ArrayList<String>();
private final Map<String, Column> map = new HashMap<>();
for (Column c1: list1) map.put(c1.name, c1);
for (Column c2: list2) {
    Column c1 = map.put(c2.name, c2);
    if (c1==null) continue;
    if (c1.type.equals(c2.type)) continue;
    conflictList.add(c1); // or add the name only or both elements or whatever
}

如果conflictList为空,则您获胜。如果您不关心细节,请尽早返回,而不是处理剩余的元素。

相关内容

最新更新