Redis存储数据类型三:Set

public class SetTest {
	public static void main(String[] args) {
		Jedis jedis = RedisUtil.getJedis();
		jedis.flushDB();   // 清空
		
		//向set集合中添加元素
		System.out.println("向set集合中添加元素:"+jedis.sadd("mySet", "a1"));
		System.out.println("向set集合中添加元素:"+jedis.sadd("mySet", "a2"));
		System.out.println("向set集合中添加元素:"+jedis.sadd("mySet", "a3"));
		System.out.println("向set集合中添加元素:"+jedis.sadd("mySet", "a4"));
		System.out.println("向set集合中添加元素:"+jedis.sadd("mySet", "a5"));
		System.out.println("向set集合中添加元素:"+jedis.sadd("mySet", "a6"));
		System.out.println("获取set集合中所有元素:"+jedis.smembers("mySet"));   //无序的
		
		//srem: 当存在对应的value时,存在删除,返回1,不存在返回0
		System.out.println("删除set集合中的某个元素:"+jedis.srem("mySet", "a6")); 
		System.out.println("获取set集合中所有元素:"+jedis.smembers("mySet"));
		
		System.out.println("随机获取集合中一个元素:"+jedis.spop("mySet"));
		
		System.out.println("查看集合中有多少个元素:"+jedis.scard("mySet"));
		
		System.out.println("判断元素在集合中是否存在:"+jedis.sismember("mySet", "123"));   // 返回true  |   false
		
		
		//两个set集合的操作
		jedis.sadd("set1", "b1","b2","b3","b4","b5");
		jedis.sadd("set2", "b1","b2","b3","b4","b5","c1","c2","c3");
		//将set2中c2这一个元素移至set1中
		//   (源set集合的Key,目标set集合的key,要移动的set集合元素)
		jedis.smove("set2", "set1", "c2");
		System.out.println("获取set1:"+jedis.smembers("set1"));
		System.out.println("获取set2:"+jedis.smembers("set2"));
		
		// 获取两个集合的交集、并集、差集
		System.out.println("交集:"+jedis.sinter("set1", "set2"));
		System.out.println("并集:"+jedis.sunion("set1","set2"));
		System.out.println("差集:"+jedis.sdiff("set1","set2"));//显示前一个不在后一个中存在的value
	}
}

你可能感兴趣的:(Redis,Redis存储数据类型三Set)