Guava Collections - Sets

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));
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值