java 如何比较java中的两个哈希集?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44355737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:07:29  来源:igfitidea点击:

How to compare two hash sets in java?

javacollectionscomparehashset

提问by user8048032

How can I compare two hash sets in java ? My first hash sets looks like below.

如何比较 java 中的两个哈希集?我的第一个哈希集如下所示。

static Set<String> nounPhrases = new HashSet<>();

Above hash set contains elements like this.

上面的哈希集包含这样的元素。

List of Noun Parse : [java, jsp, book]

名词解析列表:[java, jsp, book]

2nd hash set

第二个哈希集

static Set<String> nounPhrases2 = new HashSet<>();

List of Noun Parse : [web, php, java,book]

名词解析列表:[web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

注意 - 我需要检查两组中是否有相同的名词。如果他们有相似的名词,那么我需要做另一项任务

回答by Bohemian

This is a wheel already invented.

这是一个已经发明的轮子。

Set#equals()compares sets in the way you would expect:

Set#equals()以您期望的方式比较集合:

set1.equals(set2)

If you want two Set variables that are both null to be "equal", then use:

如果您希望两个都为 null 的 Set 变量“相等”,请使用:

Objects.equals(set1, set2)

回答by Dennux

So you mean like this?

所以你的意思是这样?

public static void main(String[] args) {

    final Set<String> nounPhrases = new HashSet<>();
    nounPhrases.add("java");
    nounPhrases.add("jsp");
    nounPhrases.add("book");

    final Set<String> nounPhrases2 = new HashSet<>();
    nounPhrases2.add("web");
    nounPhrases2.add("php");
    nounPhrases2.add("java");
    nounPhrases2.add("book");

    // Checking for every element in first set
    for (final String element : nounPhrases) {

        // if second set has the current element
        if (nounPhrases2.contains(element)) {
            System.out.println("They have " + element);
        }
    }
}

My output:

我的输出:

They have java
They have book

Edit: Based on your comment, if i understand correctly, if you want to get the common elements in both sets, just store the values and return them:

编辑:根据您的评论,如果我理解正确,如果您想获取两个集合中的公共元素,只需存储值并返回它们:

public static void main(String[] args) {

    final Set<String> nounPhrases = new HashSet<>();
    nounPhrases.add("java");
    nounPhrases.add("jsp");
    nounPhrases.add("book");

    final Set<String> nounPhrases2 = new HashSet<>();
    nounPhrases2.add("web");
    nounPhrases2.add("php");
    nounPhrases2.add("java");
    nounPhrases2.add("book");

    System.out.println(getCommon(nounPhrases, nounPhrases2));
}

public final static Set<String> getCommon(Set<String> setA, Set<String> setB) {

    final Set<String> result = new HashSet<>();
    for (final String element : setA) {
        if (setB.contains(element)) {
            result.add(element);
        }
    }
    return result;
}

You could use generics to make the method work for other elements than strings:

您可以使用泛型使该方法适用于字符串以外的其他元素:

public final static <T> Set<T> getCommon(Set<T> setA, Set<T> setB) {

    final Set<T> result = new HashSet<>();
    for (final T element : setA) {
        if (setB.contains(element)) {
            result.add(element);
        }
    }
    return result;
}

If performance is important, you should check sizes first and only iterate over the elements of the smaller set. If you have one set with 1 elements, and one set with 100, starting with the smaller will leve you with one iteration whereas starting with the bigger will leave you with 100 checks where only 1 could have been in both sets.

如果性能很重要,您应该首先检查大小,并且只迭代较小集合的元素。如果你有一个有 1 个元素的集合,一个有 100 个元素的集合,从较小的开始会让你进行一次迭代,而从较大的开始会给你留下 100 个检查,而这两个集合中只有 1 个。

回答by UchihaObito

If u want to find the common element then use collect(Collectors.toList()) instead of count , If u want simply to find how many set has common element using java 8

如果您想找到公共元素,则使用 collect(Collectors.toList()) 而不是 count ,如果您只想使用 java 8 查找有多少集合具有公共元素

long count = nounPhrases.stream().filter(tempstring -> {
            return nounPhrases2.stream().anyMatch(tempstring2 -> {
                return tempstring.equals(tempstring2);
            });
        }).count();
        if (count > 0)
            System.out.println("has common elements-"+count);
        else
            System.out.println("not common");

回答by Mayur Ingle

By the use of Java apache.commons.collections package we can implement

通过使用Java apache.commons.collections包我们可以实现

package com.StackoverFlow;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
public class MainClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub


        Set hs_1 = new HashSet();
        hs_1.add("A");
        hs_1.add("B");
        hs_1.add("C");
        hs_1.add("D");

        Set hs_2 = new HashSet();
        hs_2.add("A");
        hs_2.add("B");
        hs_2.add("C");
        hs_2.add("D");

        Collection result = CollectionUtils.subtract(hs_1, hs_2);
        System.out.println(result);
        if(result.isEmpty()){
            System.out.println("perform Task-->>Value maches  ");

        }else{
            System.out.println("perform Task-->>Value not maches  ");
        }

    }

}

回答by Binu

public class SetUtils {

    public static boolean equals(Set<?> set1, Set<?> set2){

        if(set1 == null || set2 ==null){
            return false;
        }

        if(set1.size()!=set2.size()){
            return false;
        }

        return set1.containsAll(set2);

    }
}