Java 使用正则表达式删除两个集合中的重复项

Java 使用正则表达式删除两个集合中的重复项,java,set,Java,Set,我有两个HashSet: 我不想使用嵌套的for循环进行比较,因为它的性能效率不高,我们可以使用正则表达式或其他方法来实现这一点吗?您可以使用它删除其他集合中存在的所有元素 Set<String> first = new HashSet<>(); first.add("LON/912"); first.add("LON/914"); Set<String> second = new HashSet<>(); second.add("LON/912

我有两个
HashSet

我不想使用嵌套的
for循环
进行比较,因为它的性能效率不高,我们可以使用
正则表达式
或其他方法来实现这一点吗?

您可以使用它删除其他集合中存在的所有元素

Set<String> first = new HashSet<>();
first.add("LON/912");
first.add("LON/914");

Set<String> second = new HashSet<>();
second.add("LON/912");

first.removeAll(second); // first now only contains "LON/912"
并制作一套:

Set<MyString> foo = new HashSet<>();
Set foo=new HashSet();
然后使用我提到的
removeAll


请注意,MyString类的上述实现仅代表您需要实现的内容。它当然不完整,至少还应该包含一个hashcode实现

集合不包含重复项。这就是集合的定义。或者你是说要删除两个集合中存在的任何元素?我想OP的问题是字符串值实际上并不等于“LON/912”和“912”,因此
removeAll
方法不起作用。你需要定制comparator@xander是的,我注意到了。我怀疑这可能是一个输入错误,但如果不是,我已经在我的答案中添加了一个额外的位。可能,但如果是一个输入错误,为什么OP要求正则表达式来比较值,如果字符串相等,这是没有意义的,但谁知道呢:D
[{LON/914},{LON/916}]
Set<String> first = new HashSet<>();
first.add("LON/912");
first.add("LON/914");

Set<String> second = new HashSet<>();
second.add("LON/912");

first.removeAll(second); // first now only contains "LON/912"
class MyString
{
    public String str;
    MyString(String str)
    {
        this.str = str;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;

        final MyString other = (MyString) obj;

        if (this.str.contains("LON/"))
        {
            return this.str.endsWith(other.str);
        }
        else
        {
            return this.str.equals(other.str);
        }
    }
}
Set<MyString> foo = new HashSet<>();