Tag Archives: Compare

Compare whether two sets are the same in Java

in Java API, it seems that there is no way to compare the contents of two sets, so we can only write one by ourselves to realize it. In fact, it is relatively simple to compare the number of records to see whether they are the same, and then see whether the contents are consistent. The test method is as follows:

public static boolean equals(Set<?> set1, Set<?> set2){
        if(set1 == null || set2 ==null){//null就直接不比了
            return false;
        }
        if(set1.size()!=set2.size()){//大小不同也不用比了
            return false;
        }
        return set1.containsAll(set2);//最后比containsAll
    }

unit test:

import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class TestSetUtils {
    @Test
    public void test1() {
        Set<String> test1 = new HashSet<>();
        test1.add("a");
        test1.add("b");
        Set<String> test2 = new HashSet<>();
        test2.add("b");
        test2.add("c");
        assertThat(SetUtils.equals(test1, test2), is(false));
    }
    @Test
    public void test2() {
        Set<String> test1 = new HashSet<>();
        test1.add("a");
        test1.add("b");
        Set<String> test2 = new HashSet<>();
        test2.add("a");
        test2.add("b");
        test2.add("c");
        assertThat(SetUtils.equals(test1, test2), is(false));
    }
    @Test
    public void test3() {
        Set<String> test1 = new HashSet<>();
        test1.add("a");
        test1.add("b");
        test1.add("c");
        Set<String> test2 = new HashSet<>();
        test2.add("a");
        test2.add("b");
        assertThat(SetUtils.equals(test1, test2), is(false));
    }
    //set ignore sequence
    @Test
    public void test4() {
        Set<String> test1 = new HashSet<>();
        test1.add("a");
        test1.add("b");
        Set<String> test2 = new HashSet<>();
        test2.add("b");
        test2.add("a");
        assertThat(SetUtils.equals(test1, test2), is(true));
    }
    @Test
    public void test5() {
        Set<String> test1 = new HashSet<>();
        test1.add("a");
        Set<String> test2 = new HashSet<>();
        test2.add("a");
        assertThat(SetUtils.equals(test1, test2), is(true));
    }
}

reproduced from: http://ju.outofmemory.cn/entry/288737