1.Maven Dependency
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.guava</groupId> <artifactId>guava</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>guava</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
2. SetTest.java
package org.fool.guava.collections.set;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.Set;
import org.junit.Test;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
public class SetTest {
@Test
public void testDifference() {
Set<String> s1 = Sets.newHashSet("1", "2", "3");
Set<String> s2 = Sets.newHashSet();
s2.add("2");
s2.add("3");
s2.add("4");
s2.add("5");
SetView<String> diff = Sets.difference(s1, s2);
diff.forEach(p -> System.out.println(p)); // return 1
System.out.println("----------");
diff = Sets.difference(s2, s1);
diff.forEach(p -> System.out.println(p)); // return 4 5
}
@Test
public void testSymmetricDifference() {
Set<String> s1 = Sets.newHashSet("1", "2", "3");
Set<String> s2 = Sets.newHashSet();
s2.add("2");
s2.add("3");
s2.add("4");
s2.add("5");
SetView<String> symmetricDiff = Sets.symmetricDifference(s1, s2);
symmetricDiff.forEach(p -> System.out.println(p)); // return 1 4 5
}
@Test
public void testIntersection() {
Set<String> s1 = Sets.newHashSet("1", "2", "3");
Set<String> s2 = Sets.newHashSet("3", "2", "4");
SetView<String> sv = Sets.intersection(s1, s2);
assertThat(sv.size() == 2 && sv.contains("2") && sv.contains("3"), equalTo(true));
sv.forEach(p -> System.out.println(p));
}
@Test
public void testUnion() {
Set<String> s1 = Sets.newHashSet("1", "2", "3");
Set<String> s2 = Sets.newHashSet("3", "2", "4");
SetView<String> sv = Sets.union(s1, s2);
assertThat(sv.size() == 4 && sv.contains("3") && sv.contains("2") && sv.contains("4") && sv.contains("1"),
equalTo(true));
sv.forEach(p -> System.out.println(p));
}
}