合并两个单词集合并去重

package cn.edu.bit.cs.exercise;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class RemoveAndAdd {
public static void main(String[] args)throws Exception
{
	BufferedReader br=new BufferedReader(new FileReader("D:\\Java源码\\文字统计\\英文文本.txt"));
	BufferedReader br2=new BufferedReader(new FileReader("D:\\Java源码\\文字统计\\英文文本2.txt"));
	List lists1=new ArrayList();
	List lists2=new ArrayList();
	String readline=null;
	while ((readline=br.readLine())!=null)
	{
		String[] wordArray1=readline.split("[^a-zA-Z]");
		for (String word:wordArray1)
		{
			if(word.length()!=0)
			{
				lists1.add(word);
			}
		}
	}
	br.close();
	while ((readline=br2.readLine())!=null)
	{
		String[] wordArray2=readline.split("[^a-zA-Z]");
		for (String word:wordArray2)
		{
			if(word.length()!=0)
			{
				lists2.add(word);
			}
		}
	}
	br2.close();
	lists1.removeAll(lists2);//首先去掉和lists2相同的字符
	lists1.addAll(lists2);//然后再加入lists2
	//去掉和list1重复的字符
	
	removeDublicate(lists1);
	Collections.sort(lists1);
	System.out.println(lists1);;
}
public static void removeDublicate(List list1)
{
	Set set=new HashSet<>();
	List newlist=new ArrayList<>();
	for (Iterator iter=list1.iterator();iter.hasNext();)
	{
		Object element=iter.next();
		if(set.add(element))
		{
			newlist.add(element);
		}
	}
	list1.clear();
	list1.addAll(newlist);
	return ;
}
}

1、注意去重的操作,主要运用hashset的判重的特点,set中没有重复的元素,若可以加入相应的元素,则直接加入新的list当中

2、排序直接利用collections类中自带的排序的方法

你可能感兴趣的:(Java个人总结)