【Sets】使用Google Guava工程中Sets工具包,实现集合的并集/交集/补集/差集

获取两个txt文档的内容~存储进集合中求集合的并集/交集/补集/差集

package com.sxd.readLines.aboutDB;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import com.google.common.collect.Sets;

public class Test {
    
    /**
     * 
     * @throws IOException
     */

    @org.junit.Test
    public void test1() throws IOException  {
        Set<String> set1 = readFile4List(new File("D:/B/1.txt"));
        Set<String> set2 = readFile4List(new File("D:/B/DB.txt"));
        
        Set<String> result1 = Sets.union(set1, set2);//合集,并集
        Set<String> result2 = Sets.intersection(set1, set2);//交集
        Set<String> result3 = Sets.difference(set1, set2);//差集 1中有而2中没有的
        Set<String> result4 = Sets.symmetricDifference(set1, set2);//相对差集 1中有2中没有  2中有1中没有的 取出来做结果
        
        //可以分别把4种不同结果 写出文件
        
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File("d:/B/result.txt")));
        bufferedWriter.write("共有:"+result1.size()+"条\r\n");
        for (String string : result1) {
            bufferedWriter.write(string+"\r\n");
        }
        bufferedWriter.close();
        
        
    }
    
    public Set<String> readFile4List(File file) throws IOException{
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        Set<String> set = new HashSet<String>();
        String str = null;
        while((str =bufferedReader.readLine()) != null){
            if(str.length() > 6){
                set.add(str.substring(3));
            }else{
                set.add(str);
            }
            
        }
        return set;
    }
    

}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值